index.ts 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984
  1. import { dynamicTool, type Tool, jsonSchema, type JSONSchema7 } from "ai"
  2. import { ConfigV1 } from "@opencode-ai/core/v1/config/config"
  3. import { serviceUse } from "@opencode-ai/core/effect/service-use"
  4. import { Client } from "@modelcontextprotocol/sdk/client/index.js"
  5. import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"
  6. import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js"
  7. import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"
  8. import { UnauthorizedError } from "@modelcontextprotocol/sdk/client/auth.js"
  9. import {
  10. CallToolResultSchema,
  11. ListToolsResultSchema,
  12. ToolSchema,
  13. type Tool as MCPToolDef,
  14. ToolListChangedNotificationSchema,
  15. } from "@modelcontextprotocol/sdk/types.js"
  16. import { Config } from "@/config/config"
  17. import { ConfigMCPV1 } from "@opencode-ai/core/v1/config/mcp"
  18. import { NamedError } from "@opencode-ai/core/util/error"
  19. import { InstallationVersion } from "@opencode-ai/core/installation/version"
  20. import { withTimeout } from "@/util/timeout"
  21. import { FSUtil } from "@opencode-ai/core/fs-util"
  22. import { McpOAuthProvider, OAUTH_CALLBACK_PATH } from "./oauth-provider"
  23. import { McpOAuthCallback } from "./oauth-callback"
  24. import { McpAuth } from "./auth"
  25. import { EventV2Bridge } from "@/event-v2-bridge"
  26. import { EventV2 } from "@opencode-ai/core/event"
  27. import { TuiEvent } from "@/server/tui-event"
  28. import open from "open"
  29. import { Effect, Exit, Layer, Option, Context, Schema, Stream } from "effect"
  30. import { EffectBridge } from "@/effect/bridge"
  31. import { InstanceState } from "@/effect/instance-state"
  32. import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"
  33. import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner"
  34. const DEFAULT_TIMEOUT = 30_000
  35. const TolerantListToolsResultSchema = ListToolsResultSchema.extend({
  36. tools: ToolSchema.omit({ outputSchema: true }).array(),
  37. })
  38. export const Resource = Schema.Struct({
  39. name: Schema.String,
  40. uri: Schema.String,
  41. description: Schema.optional(Schema.String),
  42. mimeType: Schema.optional(Schema.String),
  43. client: Schema.String,
  44. }).annotate({ identifier: "McpResource" })
  45. export type Resource = Schema.Schema.Type<typeof Resource>
  46. export const ToolsChanged = EventV2.define({
  47. type: "mcp.tools.changed",
  48. schema: {
  49. server: Schema.String,
  50. },
  51. })
  52. export const BrowserOpenFailed = EventV2.define({
  53. type: "mcp.browser.open.failed",
  54. schema: {
  55. mcpName: Schema.String,
  56. url: Schema.String,
  57. },
  58. })
  59. export const Failed = NamedError.create("MCPFailed", {
  60. name: Schema.String,
  61. })
  62. export class NotFoundError extends Schema.TaggedErrorClass<NotFoundError>()("MCP.NotFoundError", {
  63. name: Schema.String,
  64. }) {}
  65. type MCPClient = Client
  66. const StatusConnected = Schema.Struct({ status: Schema.Literal("connected") }).annotate({
  67. identifier: "MCPStatusConnected",
  68. })
  69. const StatusDisabled = Schema.Struct({ status: Schema.Literal("disabled") }).annotate({
  70. identifier: "MCPStatusDisabled",
  71. })
  72. const StatusFailed = Schema.Struct({ status: Schema.Literal("failed"), error: Schema.String }).annotate({
  73. identifier: "MCPStatusFailed",
  74. })
  75. const StatusNeedsAuth = Schema.Struct({ status: Schema.Literal("needs_auth") }).annotate({
  76. identifier: "MCPStatusNeedsAuth",
  77. })
  78. const StatusNeedsClientRegistration = Schema.Struct({
  79. status: Schema.Literal("needs_client_registration"),
  80. error: Schema.String,
  81. }).annotate({ identifier: "MCPStatusNeedsClientRegistration" })
  82. export const Status = Schema.Union([
  83. StatusConnected,
  84. StatusDisabled,
  85. StatusFailed,
  86. StatusNeedsAuth,
  87. StatusNeedsClientRegistration,
  88. ]).annotate({ identifier: "MCPStatus", discriminator: "status" })
  89. export type Status = Schema.Schema.Type<typeof Status>
  90. // Store transports for OAuth servers to allow finishing auth
  91. type TransportWithAuth = StreamableHTTPClientTransport | SSEClientTransport
  92. const pendingOAuthTransports = new Map<string, TransportWithAuth>()
  93. // Prompt cache types
  94. type PromptInfo = Awaited<ReturnType<MCPClient["listPrompts"]>>["prompts"][number]
  95. type ResourceInfo = Awaited<ReturnType<MCPClient["listResources"]>>["resources"][number]
  96. type McpEntry = NonNullable<ConfigV1.Info["mcp"]>[string]
  97. function isMcpConfigured(entry: McpEntry): entry is ConfigMCPV1.Info {
  98. return typeof entry === "object" && entry !== null && "type" in entry
  99. }
  100. const sanitize = (s: string) => s.replace(/[^a-zA-Z0-9_-]/g, "_")
  101. const MAX_LIST_PAGES = 1_000
  102. function remoteURL(key: string, value: string) {
  103. if (URL.canParse(value)) return new URL(value)
  104. }
  105. function isOutputSchemaValidationError(error: Error) {
  106. return /can't resolve reference|resolves to more than one schema|outputSchema|schema.*reference|reference.*schema/i.test(
  107. error.message,
  108. )
  109. }
  110. async function paginate<T, R extends { nextCursor?: string }>(
  111. list: (cursor?: string) => Promise<R>,
  112. items: (result: R) => T[],
  113. ) {
  114. const result: T[] = []
  115. const cursors = new Set<string>()
  116. let cursor: string | undefined
  117. for (let page = 0; page < MAX_LIST_PAGES; page++) {
  118. const page = await list(cursor)
  119. result.push(...items(page))
  120. if (page.nextCursor === undefined) return result
  121. if (cursors.has(page.nextCursor)) throw new Error(`MCP list returned duplicate cursor: ${page.nextCursor}`)
  122. cursors.add(page.nextCursor)
  123. cursor = page.nextCursor
  124. }
  125. throw new Error(`MCP list exceeded ${MAX_LIST_PAGES} pages`)
  126. }
  127. function listTools(client: MCPClient, timeout: number) {
  128. return Effect.tryPromise({
  129. try: () =>
  130. paginate(
  131. async (cursor) => {
  132. const params = cursor === undefined ? undefined : { cursor }
  133. try {
  134. return await client.listTools(params, { timeout })
  135. } catch (error) {
  136. if (!(error instanceof Error) || !isOutputSchemaValidationError(error)) throw error
  137. return client.request({ method: "tools/list", params }, TolerantListToolsResultSchema, { timeout })
  138. }
  139. },
  140. (result) => result.tools,
  141. ),
  142. catch: (err) => (err instanceof Error ? err : new Error(String(err))),
  143. })
  144. }
  145. // Convert MCP tool definition to AI SDK Tool type
  146. function convertMcpTool(mcpTool: MCPToolDef, client: MCPClient, timeout?: number): Tool {
  147. const inputSchema = mcpTool.inputSchema
  148. // Spread first, then override type to ensure it's always "object"
  149. const schema: JSONSchema7 = {
  150. ...(inputSchema as JSONSchema7),
  151. type: "object",
  152. properties: (inputSchema.properties ?? {}) as JSONSchema7["properties"],
  153. additionalProperties: false,
  154. }
  155. return dynamicTool({
  156. description: mcpTool.description ?? "",
  157. inputSchema: jsonSchema(schema),
  158. execute: async (args: unknown) => {
  159. return client.callTool(
  160. {
  161. name: mcpTool.name,
  162. arguments: (args || {}) as Record<string, unknown>,
  163. },
  164. CallToolResultSchema,
  165. {
  166. resetTimeoutOnProgress: true,
  167. timeout,
  168. },
  169. )
  170. },
  171. })
  172. }
  173. function defs(client: MCPClient, timeout?: number) {
  174. return listTools(client, timeout ?? DEFAULT_TIMEOUT).pipe(
  175. Effect.catch((err) => {
  176. return Effect.succeed(undefined)
  177. }),
  178. )
  179. }
  180. function fetchFromClient<T extends { name: string }>(
  181. clientName: string,
  182. client: Client,
  183. listFn: (c: Client) => Promise<T[]>,
  184. label: string,
  185. ) {
  186. return Effect.tryPromise({
  187. try: () => listFn(client),
  188. catch: (e: any) => {
  189. return e
  190. },
  191. }).pipe(
  192. Effect.map((items) => {
  193. const out: Record<string, T & { client: string }> = {}
  194. const sanitizedClient = sanitize(clientName)
  195. for (const item of items) {
  196. out[sanitizedClient + ":" + sanitize(item.name)] = { ...item, client: clientName }
  197. }
  198. return out
  199. }),
  200. Effect.orElseSucceed(() => undefined),
  201. )
  202. }
  203. interface CreateResult {
  204. mcpClient?: MCPClient
  205. status: Status
  206. defs?: MCPToolDef[]
  207. }
  208. interface AuthResult {
  209. authorizationUrl: string
  210. oauthState: string
  211. client?: MCPClient
  212. }
  213. // --- Effect Service ---
  214. interface State {
  215. config: Record<string, ConfigMCPV1.Info>
  216. status: Record<string, Status>
  217. clients: Record<string, MCPClient>
  218. defs: Record<string, MCPToolDef[]>
  219. }
  220. export interface Interface {
  221. readonly status: () => Effect.Effect<Record<string, Status>>
  222. readonly clients: () => Effect.Effect<Record<string, MCPClient>>
  223. readonly tools: () => Effect.Effect<Record<string, Tool>>
  224. readonly prompts: () => Effect.Effect<Record<string, PromptInfo & { client: string }>>
  225. readonly resources: () => Effect.Effect<Record<string, ResourceInfo & { client: string }>>
  226. readonly add: (name: string, mcp: ConfigMCPV1.Info) => Effect.Effect<{ status: Record<string, Status> | Status }>
  227. readonly connect: (name: string) => Effect.Effect<void, NotFoundError>
  228. readonly disconnect: (name: string) => Effect.Effect<void, NotFoundError>
  229. readonly getPrompt: (
  230. clientName: string,
  231. name: string,
  232. args?: Record<string, string>,
  233. ) => Effect.Effect<Awaited<ReturnType<MCPClient["getPrompt"]>> | undefined>
  234. readonly readResource: (
  235. clientName: string,
  236. resourceUri: string,
  237. ) => Effect.Effect<Awaited<ReturnType<MCPClient["readResource"]>> | undefined>
  238. readonly startAuth: (
  239. mcpName: string,
  240. ) => Effect.Effect<{ authorizationUrl: string; oauthState: string }, NotFoundError>
  241. readonly authenticate: (mcpName: string) => Effect.Effect<Status, NotFoundError>
  242. readonly finishAuth: (mcpName: string, authorizationCode: string) => Effect.Effect<Status, NotFoundError>
  243. readonly removeAuth: (mcpName: string) => Effect.Effect<void>
  244. readonly supportsOAuth: (mcpName: string) => Effect.Effect<boolean, NotFoundError>
  245. readonly hasStoredTokens: (mcpName: string) => Effect.Effect<boolean>
  246. readonly getAuthStatus: (mcpName: string) => Effect.Effect<AuthStatus>
  247. }
  248. export class Service extends Context.Service<Service, Interface>()("@opencode/MCP") {}
  249. export const use = serviceUse(Service)
  250. export const layer = Layer.effect(
  251. Service,
  252. Effect.gen(function* () {
  253. const spawner = yield* ChildProcessSpawner.ChildProcessSpawner
  254. const auth = yield* McpAuth.Service
  255. const events = yield* EventV2Bridge.Service
  256. type Transport = StdioClientTransport | StreamableHTTPClientTransport | SSEClientTransport
  257. /**
  258. * Connect a client via the given transport with resource safety:
  259. * on failure the transport is closed; on success the caller owns it.
  260. */
  261. const connectTransport = (transport: Transport, timeout: number) =>
  262. Effect.acquireUseRelease(
  263. Effect.succeed(transport),
  264. (t) =>
  265. Effect.tryPromise({
  266. try: () => {
  267. const client = new Client({ name: "opencode", version: InstallationVersion })
  268. return withTimeout(client.connect(t), timeout).then(() => client)
  269. },
  270. catch: (e) => (e instanceof Error ? e : new Error(String(e))),
  271. }),
  272. (t, exit) => (Exit.isFailure(exit) ? Effect.tryPromise(() => t.close()).pipe(Effect.ignore) : Effect.void),
  273. )
  274. const DISABLED_RESULT: CreateResult = { status: { status: "disabled" } }
  275. const connectRemote = Effect.fn("MCP.connectRemote")(function* (
  276. key: string,
  277. mcp: ConfigMCPV1.Info & { type: "remote" },
  278. ) {
  279. const oauthDisabled = mcp.oauth === false
  280. const oauthConfig = typeof mcp.oauth === "object" ? mcp.oauth : undefined
  281. const url = remoteURL(key, mcp.url)
  282. if (!url) {
  283. return {
  284. client: undefined as MCPClient | undefined,
  285. status: { status: "failed" as const, error: `Invalid MCP URL for "${key}"` },
  286. }
  287. }
  288. let authProvider: McpOAuthProvider | undefined
  289. if (!oauthDisabled) {
  290. authProvider = new McpOAuthProvider(
  291. key,
  292. mcp.url,
  293. {
  294. clientId: oauthConfig?.clientId,
  295. clientSecret: oauthConfig?.clientSecret,
  296. scope: oauthConfig?.scope,
  297. callbackPort: oauthConfig?.callbackPort,
  298. redirectUri: oauthConfig?.redirectUri,
  299. },
  300. {
  301. onRedirect: async () => {},
  302. },
  303. auth,
  304. )
  305. }
  306. const transports: Array<{ name: string; transport: TransportWithAuth }> = [
  307. {
  308. name: "StreamableHTTP",
  309. transport: new StreamableHTTPClientTransport(url, {
  310. authProvider,
  311. requestInit: mcp.headers ? { headers: mcp.headers } : undefined,
  312. }),
  313. },
  314. {
  315. name: "SSE",
  316. transport: new SSEClientTransport(url, {
  317. authProvider,
  318. requestInit: mcp.headers ? { headers: mcp.headers } : undefined,
  319. }),
  320. },
  321. ]
  322. const connectTimeout = mcp.timeout ?? DEFAULT_TIMEOUT
  323. let lastStatus: Status | undefined
  324. for (const { name, transport } of transports) {
  325. const result = yield* connectTransport(transport, connectTimeout).pipe(
  326. Effect.map((client) => ({ client, transportName: name })),
  327. Effect.catch((error) => {
  328. const lastError = error instanceof Error ? error : new Error(String(error))
  329. const isAuthError =
  330. error instanceof UnauthorizedError || (authProvider && lastError.message.includes("OAuth"))
  331. if (isAuthError) {
  332. if (lastError.message.includes("registration") || lastError.message.includes("client_id")) {
  333. lastStatus = {
  334. status: "needs_client_registration" as const,
  335. error: "Server does not support dynamic client registration. Please provide clientId in config.",
  336. }
  337. return events
  338. .publish(TuiEvent.ToastShow, {
  339. title: "MCP Authentication Required",
  340. message: `Server "${key}" requires a pre-registered client ID. Add clientId to your config.`,
  341. variant: "warning",
  342. duration: 8000,
  343. })
  344. .pipe(Effect.ignore, Effect.as(undefined))
  345. } else {
  346. pendingOAuthTransports.set(key, transport)
  347. lastStatus = { status: "needs_auth" as const }
  348. return events
  349. .publish(TuiEvent.ToastShow, {
  350. title: "MCP Authentication Required",
  351. message: `Server "${key}" requires authentication. Run: opencode mcp auth ${key}`,
  352. variant: "warning",
  353. duration: 8000,
  354. })
  355. .pipe(Effect.ignore, Effect.as(undefined))
  356. }
  357. }
  358. lastStatus = { status: "failed" as const, error: lastError.message }
  359. return Effect.succeed(undefined)
  360. }),
  361. )
  362. if (result) {
  363. return { client: result.client as MCPClient | undefined, status: { status: "connected" } as Status }
  364. }
  365. // If this was an auth error, stop trying other transports
  366. if (lastStatus?.status === "needs_auth" || lastStatus?.status === "needs_client_registration") break
  367. }
  368. return {
  369. client: undefined as MCPClient | undefined,
  370. status: (lastStatus ?? { status: "failed", error: "Unknown error" }) as Status,
  371. }
  372. })
  373. const connectLocal = Effect.fn("MCP.connectLocal")(function* (
  374. key: string,
  375. mcp: ConfigMCPV1.Info & { type: "local" },
  376. ) {
  377. const [cmd, ...args] = mcp.command
  378. const cwd = yield* InstanceState.directory
  379. const transport = new StdioClientTransport({
  380. stderr: "pipe",
  381. command: cmd,
  382. args,
  383. cwd,
  384. env: {
  385. ...process.env,
  386. ...(cmd === "opencode" ? { BUN_BE_BUN: "1" } : {}),
  387. ...mcp.environment,
  388. },
  389. })
  390. const connectTimeout = mcp.timeout ?? DEFAULT_TIMEOUT
  391. return yield* connectTransport(transport, connectTimeout).pipe(
  392. Effect.map((client): { client: MCPClient | undefined; status: Status } => ({
  393. client,
  394. status: { status: "connected" },
  395. })),
  396. Effect.catch((error): Effect.Effect<{ client: MCPClient | undefined; status: Status }> => {
  397. const msg = error instanceof Error ? error.message : String(error)
  398. return Effect.succeed({ client: undefined, status: { status: "failed", error: msg } })
  399. }),
  400. )
  401. })
  402. const create = Effect.fn("MCP.create")(function* (key: string, mcp: ConfigMCPV1.Info) {
  403. if (mcp.enabled === false) {
  404. return DISABLED_RESULT
  405. }
  406. const { client: mcpClient, status } =
  407. mcp.type === "remote"
  408. ? yield* connectRemote(key, mcp as ConfigMCPV1.Info & { type: "remote" })
  409. : yield* connectLocal(key, mcp as ConfigMCPV1.Info & { type: "local" })
  410. if (!mcpClient) {
  411. return { status } satisfies CreateResult
  412. }
  413. const listed = mcpClient.getServerCapabilities()?.tools ? yield* defs(mcpClient, mcp.timeout) : []
  414. if (!listed) {
  415. yield* Effect.tryPromise(() => mcpClient.close()).pipe(Effect.ignore)
  416. return { status: { status: "failed", error: "Failed to get tools" } } satisfies CreateResult
  417. }
  418. return { mcpClient, status, defs: listed } satisfies CreateResult
  419. })
  420. const cfgSvc = yield* Config.Service
  421. const descendants = Effect.fnUntraced(
  422. function* (pid: number) {
  423. if (process.platform === "win32") return [] as number[]
  424. const pids: number[] = []
  425. const queue = [pid]
  426. while (queue.length > 0) {
  427. const current = queue.shift()!
  428. const handle = yield* spawner.spawn(ChildProcess.make("pgrep", ["-P", String(current)], { stdin: "ignore" }))
  429. const text = yield* Stream.mkString(Stream.decodeText(handle.stdout))
  430. yield* handle.exitCode
  431. for (const tok of text.split("\n")) {
  432. const cpid = parseInt(tok, 10)
  433. if (!isNaN(cpid) && !pids.includes(cpid)) {
  434. pids.push(cpid)
  435. queue.push(cpid)
  436. }
  437. }
  438. }
  439. return pids
  440. },
  441. Effect.scoped,
  442. Effect.catch(() => Effect.succeed([] as number[])),
  443. )
  444. function watch(s: State, name: string, client: MCPClient, bridge: EffectBridge.Shape, timeout?: number) {
  445. if (!client.getServerCapabilities()?.tools) return
  446. client.setNotificationHandler(ToolListChangedNotificationSchema, async () => {
  447. if (s.clients[name] !== client || s.status[name]?.status !== "connected") return
  448. const listed = await bridge.promise(defs(client, timeout))
  449. if (!listed) return
  450. if (s.clients[name] !== client || s.status[name]?.status !== "connected") return
  451. s.defs[name] = listed
  452. await bridge.promise(events.publish(ToolsChanged, { server: name }).pipe(Effect.ignore))
  453. })
  454. }
  455. const state = yield* InstanceState.make<State>(
  456. Effect.fn("MCP.state")(function* () {
  457. const cfg = yield* cfgSvc.get()
  458. const bridge = yield* EffectBridge.make()
  459. const config = cfg.mcp ?? {}
  460. const s: State = {
  461. config: {},
  462. status: {},
  463. clients: {},
  464. defs: {},
  465. }
  466. yield* Effect.forEach(
  467. Object.entries(config),
  468. ([key, mcp]) =>
  469. Effect.gen(function* () {
  470. if (!isMcpConfigured(mcp)) {
  471. return
  472. }
  473. if (mcp.enabled === false) {
  474. s.status[key] = { status: "disabled" }
  475. return
  476. }
  477. const result = yield* create(key, mcp).pipe(Effect.catch(() => Effect.void))
  478. if (!result) return
  479. s.status[key] = result.status
  480. if (result.mcpClient) {
  481. s.clients[key] = result.mcpClient
  482. s.defs[key] = result.defs!
  483. watch(s, key, result.mcpClient, bridge, mcp.timeout)
  484. }
  485. }),
  486. { concurrency: "unbounded" },
  487. )
  488. yield* Effect.addFinalizer(() =>
  489. Effect.gen(function* () {
  490. yield* Effect.forEach(
  491. Object.values(s.clients),
  492. (client) =>
  493. Effect.gen(function* () {
  494. const pid = client.transport instanceof StdioClientTransport ? client.transport.pid : null
  495. if (typeof pid === "number") {
  496. const pids = yield* descendants(pid)
  497. for (const dpid of pids) {
  498. try {
  499. process.kill(dpid, "SIGTERM")
  500. } catch {}
  501. }
  502. }
  503. yield* Effect.tryPromise(() => client.close()).pipe(Effect.ignore)
  504. }),
  505. { concurrency: "unbounded" },
  506. )
  507. pendingOAuthTransports.clear()
  508. }),
  509. )
  510. return s
  511. }),
  512. )
  513. function closeClient(s: State, name: string) {
  514. const client = s.clients[name]
  515. delete s.defs[name]
  516. if (!client) return Effect.void
  517. return Effect.tryPromise(() => client.close()).pipe(Effect.ignore)
  518. }
  519. const storeClient = Effect.fnUntraced(function* (
  520. s: State,
  521. name: string,
  522. client: MCPClient,
  523. listed: MCPToolDef[],
  524. timeout?: number,
  525. ) {
  526. const bridge = yield* EffectBridge.make()
  527. yield* closeClient(s, name)
  528. s.status[name] = { status: "connected" }
  529. s.clients[name] = client
  530. s.defs[name] = listed
  531. watch(s, name, client, bridge, timeout)
  532. return s.status[name]
  533. })
  534. const status = Effect.fn("MCP.status")(function* () {
  535. const s = yield* InstanceState.get(state)
  536. const cfg = yield* cfgSvc.get()
  537. const config = cfg.mcp ?? {}
  538. const result: Record<string, Status> = {}
  539. for (const [key, mcp] of Object.entries(config)) {
  540. if (!isMcpConfigured(mcp)) continue
  541. result[key] = s.status[key] ?? { status: "disabled" }
  542. }
  543. for (const key of Object.keys(s.config)) {
  544. result[key] = s.status[key] ?? { status: "disabled" }
  545. }
  546. return result
  547. })
  548. const clients = Effect.fn("MCP.clients")(function* () {
  549. const s = yield* InstanceState.get(state)
  550. return s.clients
  551. })
  552. const createAndStore = Effect.fn("MCP.createAndStore")(function* (name: string, mcp: ConfigMCPV1.Info) {
  553. const s = yield* InstanceState.get(state)
  554. const result = yield* create(name, mcp)
  555. s.status[name] = result.status
  556. if (!result.mcpClient) {
  557. yield* closeClient(s, name)
  558. delete s.clients[name]
  559. return result.status
  560. }
  561. return yield* storeClient(s, name, result.mcpClient, result.defs!, mcp.timeout)
  562. })
  563. const add = Effect.fn("MCP.add")(function* (name: string, mcp: ConfigMCPV1.Info) {
  564. const s = yield* InstanceState.get(state)
  565. s.config[name] = mcp
  566. yield* createAndStore(name, mcp)
  567. return { status: s.status }
  568. })
  569. const connect = Effect.fn("MCP.connect")(function* (name: string) {
  570. const mcp = yield* requireMcpConfig(name)
  571. yield* createAndStore(name, { ...mcp, enabled: true })
  572. })
  573. const disconnect = Effect.fn("MCP.disconnect")(function* (name: string) {
  574. yield* requireMcpConfig(name)
  575. const s = yield* InstanceState.get(state)
  576. yield* closeClient(s, name)
  577. delete s.clients[name]
  578. s.status[name] = { status: "disabled" }
  579. })
  580. const tools = Effect.fn("MCP.tools")(function* () {
  581. const result: Record<string, Tool> = {}
  582. const s = yield* InstanceState.get(state)
  583. const cfg = yield* cfgSvc.get()
  584. const config = cfg.mcp ?? {}
  585. const defaultTimeout = cfg.experimental?.mcp_timeout
  586. const connectedClients = Object.entries(s.clients).filter(
  587. ([clientName]) => s.status[clientName]?.status === "connected",
  588. )
  589. yield* Effect.forEach(
  590. connectedClients,
  591. ([clientName, client]) =>
  592. Effect.gen(function* () {
  593. const mcpConfig = config[clientName]
  594. const entry = mcpConfig && isMcpConfigured(mcpConfig) ? mcpConfig : s.config[clientName]
  595. const listed = s.defs[clientName]
  596. if (!listed) {
  597. return
  598. }
  599. const timeout = entry?.timeout ?? defaultTimeout
  600. for (const mcpTool of listed) {
  601. result[sanitize(clientName) + "_" + sanitize(mcpTool.name)] = convertMcpTool(mcpTool, client, timeout)
  602. }
  603. }),
  604. { concurrency: "unbounded" },
  605. )
  606. return result
  607. })
  608. function collectFromConnected<T extends { name: string }>(
  609. s: State,
  610. listFn: (c: Client) => Promise<T[]>,
  611. label: string,
  612. ) {
  613. return Effect.forEach(
  614. Object.entries(s.clients).filter(([name]) => s.status[name]?.status === "connected"),
  615. ([clientName, client]) =>
  616. fetchFromClient(clientName, client, listFn, label).pipe(Effect.map((items) => Object.entries(items ?? {}))),
  617. { concurrency: "unbounded" },
  618. ).pipe(Effect.map((results) => Object.fromEntries<T & { client: string }>(results.flat())))
  619. }
  620. const prompts = Effect.fn("MCP.prompts")(function* () {
  621. const s = yield* InstanceState.get(state)
  622. return yield* collectFromConnected(
  623. s,
  624. (c) =>
  625. c.getServerCapabilities()?.prompts
  626. ? paginate(
  627. (cursor) => c.listPrompts(cursor === undefined ? undefined : { cursor }),
  628. (result) => result.prompts,
  629. )
  630. : Promise.resolve([]),
  631. "prompts",
  632. )
  633. })
  634. const resources = Effect.fn("MCP.resources")(function* () {
  635. const s = yield* InstanceState.get(state)
  636. return yield* collectFromConnected(
  637. s,
  638. (c) =>
  639. c.getServerCapabilities()?.resources
  640. ? paginate(
  641. (cursor) => c.listResources(cursor === undefined ? undefined : { cursor }),
  642. (result) => result.resources,
  643. )
  644. : Promise.resolve([]),
  645. "resources",
  646. )
  647. })
  648. const withClient = Effect.fnUntraced(function* <A>(
  649. clientName: string,
  650. fn: (client: MCPClient) => Promise<A>,
  651. label: string,
  652. meta?: Record<string, unknown>,
  653. ) {
  654. const s = yield* InstanceState.get(state)
  655. const client = s.clients[clientName]
  656. if (!client) {
  657. return undefined
  658. }
  659. return yield* Effect.tryPromise({
  660. try: () => fn(client),
  661. catch: (e: any) => {
  662. return e
  663. },
  664. }).pipe(Effect.orElseSucceed(() => undefined))
  665. })
  666. const getPrompt = Effect.fn("MCP.getPrompt")(function* (
  667. clientName: string,
  668. name: string,
  669. args?: Record<string, string>,
  670. ) {
  671. return yield* withClient(clientName, (client) => client.getPrompt({ name, arguments: args }), "getPrompt", {
  672. promptName: name,
  673. })
  674. })
  675. const readResource = Effect.fn("MCP.readResource")(function* (clientName: string, resourceUri: string) {
  676. return yield* withClient(clientName, (client) => client.readResource({ uri: resourceUri }), "readResource", {
  677. resourceUri,
  678. })
  679. })
  680. const getMcpConfig = Effect.fnUntraced(function* (mcpName: string) {
  681. const s = yield* InstanceState.get(state)
  682. if (s.config[mcpName]) return s.config[mcpName]
  683. const cfg = yield* cfgSvc.get()
  684. const mcpConfig = cfg.mcp?.[mcpName]
  685. if (!mcpConfig || !isMcpConfigured(mcpConfig)) return undefined
  686. return mcpConfig
  687. })
  688. const requireMcpConfig = Effect.fnUntraced(function* (mcpName: string) {
  689. const mcpConfig = yield* getMcpConfig(mcpName)
  690. if (!mcpConfig) return yield* new NotFoundError({ name: mcpName })
  691. return mcpConfig
  692. })
  693. const startAuth = Effect.fn("MCP.startAuth")(function* (mcpName: string) {
  694. const mcpConfig = yield* requireMcpConfig(mcpName)
  695. if (mcpConfig.type !== "remote") throw new Error(`MCP server ${mcpName} is not a remote server`)
  696. if (mcpConfig.oauth === false) throw new Error(`MCP server ${mcpName} has OAuth explicitly disabled`)
  697. const url = remoteURL(mcpName, mcpConfig.url)
  698. if (!url) throw new Error(`Invalid MCP URL for "${mcpName}"`)
  699. // OAuth config is optional - if not provided, we'll use auto-discovery
  700. const oauthConfig = typeof mcpConfig.oauth === "object" ? mcpConfig.oauth : undefined
  701. // Resolve effective redirect URI: explicit redirectUri > callbackPort shorthand > default
  702. const effectiveRedirectUri =
  703. oauthConfig?.redirectUri ??
  704. (oauthConfig?.callbackPort ? `http://127.0.0.1:${oauthConfig.callbackPort}${OAUTH_CALLBACK_PATH}` : undefined)
  705. // Start the callback server with custom redirectUri if configured
  706. yield* Effect.promise(() => McpOAuthCallback.ensureRunning(effectiveRedirectUri))
  707. const oauthState = Array.from(crypto.getRandomValues(new Uint8Array(32)))
  708. .map((b) => b.toString(16).padStart(2, "0"))
  709. .join("")
  710. yield* auth.updateOAuthState(mcpName, oauthState)
  711. let capturedUrl: URL | undefined
  712. const authProvider = new McpOAuthProvider(
  713. mcpName,
  714. mcpConfig.url,
  715. {
  716. clientId: oauthConfig?.clientId,
  717. clientSecret: oauthConfig?.clientSecret,
  718. scope: oauthConfig?.scope,
  719. redirectUri: effectiveRedirectUri,
  720. },
  721. {
  722. onRedirect: async (url) => {
  723. capturedUrl = url
  724. },
  725. },
  726. auth,
  727. )
  728. const transport = new StreamableHTTPClientTransport(url, { authProvider })
  729. return yield* Effect.tryPromise({
  730. try: () => {
  731. const client = new Client({ name: "opencode", version: InstallationVersion })
  732. return client
  733. .connect(transport)
  734. .then(() => ({ authorizationUrl: "", oauthState, client }) satisfies AuthResult)
  735. },
  736. catch: (error) => error,
  737. }).pipe(
  738. Effect.catch((error) => {
  739. if (error instanceof UnauthorizedError && capturedUrl) {
  740. pendingOAuthTransports.set(mcpName, transport)
  741. return Effect.succeed({ authorizationUrl: capturedUrl.toString(), oauthState } satisfies AuthResult)
  742. }
  743. return Effect.die(error)
  744. }),
  745. )
  746. })
  747. const authenticate = Effect.fn("MCP.authenticate")(function* (mcpName: string) {
  748. const result = yield* startAuth(mcpName)
  749. if (!result.authorizationUrl) {
  750. const client = "client" in result ? result.client : undefined
  751. const mcpConfig = yield* requireMcpConfig(mcpName).pipe(
  752. Effect.tapError(() => Effect.tryPromise(() => client?.close() ?? Promise.resolve()).pipe(Effect.ignore)),
  753. )
  754. const listed = client
  755. ? client.getServerCapabilities()?.tools
  756. ? yield* defs(client, mcpConfig.timeout)
  757. : []
  758. : undefined
  759. if (!client || !listed) {
  760. yield* Effect.tryPromise(() => client?.close() ?? Promise.resolve()).pipe(Effect.ignore)
  761. return { status: "failed", error: "Failed to get tools" } as Status
  762. }
  763. const s = yield* InstanceState.get(state)
  764. yield* auth.clearOAuthState(mcpName)
  765. return yield* storeClient(s, mcpName, client, listed, mcpConfig.timeout)
  766. }
  767. const callbackPromise = McpOAuthCallback.waitForCallback(result.oauthState, mcpName)
  768. yield* Effect.tryPromise(() => open(result.authorizationUrl)).pipe(
  769. Effect.flatMap((subprocess) =>
  770. Effect.callback<void, Error>((resume) => {
  771. const timer = setTimeout(() => resume(Effect.void), 500)
  772. subprocess.on("error", (err) => {
  773. clearTimeout(timer)
  774. resume(Effect.fail(err))
  775. })
  776. subprocess.on("exit", (code) => {
  777. if (code !== null && code !== 0) {
  778. clearTimeout(timer)
  779. resume(Effect.fail(new Error(`Browser open failed with exit code ${code}`)))
  780. }
  781. })
  782. }),
  783. ),
  784. Effect.catch(() => {
  785. return events.publish(BrowserOpenFailed, { mcpName, url: result.authorizationUrl }).pipe(Effect.ignore)
  786. }),
  787. )
  788. const code = yield* Effect.promise(() => callbackPromise)
  789. const storedState = yield* auth.getOAuthState(mcpName)
  790. if (storedState !== result.oauthState) {
  791. yield* auth.clearOAuthState(mcpName)
  792. throw new Error("OAuth state mismatch - potential CSRF attack")
  793. }
  794. yield* auth.clearOAuthState(mcpName)
  795. return yield* finishAuth(mcpName, code)
  796. })
  797. const finishAuth = Effect.fn("MCP.finishAuth")(function* (mcpName: string, authorizationCode: string) {
  798. yield* requireMcpConfig(mcpName)
  799. const transport = pendingOAuthTransports.get(mcpName)
  800. if (!transport) throw new Error(`No pending OAuth flow for MCP server: ${mcpName}`)
  801. const result = yield* Effect.tryPromise({
  802. try: () => transport.finishAuth(authorizationCode).then(() => true as const),
  803. catch: (error) => {
  804. return error
  805. },
  806. }).pipe(Effect.option)
  807. if (Option.isNone(result)) {
  808. return { status: "failed", error: "OAuth completion failed" } as Status
  809. }
  810. yield* auth.clearCodeVerifier(mcpName)
  811. pendingOAuthTransports.delete(mcpName)
  812. const mcpConfig = yield* requireMcpConfig(mcpName)
  813. return yield* createAndStore(mcpName, mcpConfig)
  814. })
  815. const removeAuth = Effect.fn("MCP.removeAuth")(function* (mcpName: string) {
  816. yield* auth.remove(mcpName)
  817. McpOAuthCallback.cancelPending(mcpName)
  818. pendingOAuthTransports.delete(mcpName)
  819. })
  820. const supportsOAuth = Effect.fn("MCP.supportsOAuth")(function* (mcpName: string) {
  821. const mcpConfig = yield* requireMcpConfig(mcpName)
  822. return mcpConfig.type === "remote" && mcpConfig.oauth !== false
  823. })
  824. const hasStoredTokens = Effect.fn("MCP.hasStoredTokens")(function* (mcpName: string) {
  825. const entry = yield* auth.get(mcpName)
  826. return !!entry?.tokens
  827. })
  828. const getAuthStatus = Effect.fn("MCP.getAuthStatus")(function* (mcpName: string) {
  829. const entry = yield* auth.get(mcpName)
  830. if (!entry?.tokens) return "not_authenticated" as AuthStatus
  831. const expired = yield* auth.isTokenExpired(mcpName)
  832. return (expired ? "expired" : "authenticated") as AuthStatus
  833. })
  834. return Service.of({
  835. status,
  836. clients,
  837. tools,
  838. prompts,
  839. resources,
  840. add,
  841. connect,
  842. disconnect,
  843. getPrompt,
  844. readResource,
  845. startAuth,
  846. authenticate,
  847. finishAuth,
  848. removeAuth,
  849. supportsOAuth,
  850. hasStoredTokens,
  851. getAuthStatus,
  852. })
  853. }),
  854. )
  855. export type AuthStatus = "authenticated" | "expired" | "not_authenticated"
  856. // --- Per-service runtime ---
  857. export const defaultLayer = layer.pipe(
  858. Layer.provide(McpAuth.defaultLayer),
  859. Layer.provide(EventV2Bridge.defaultLayer),
  860. Layer.provide(Config.defaultLayer),
  861. Layer.provide(CrossSpawnSpawner.defaultLayer),
  862. Layer.provide(FSUtil.defaultLayer),
  863. )
  864. export * as MCP from "."