index.ts 34 KB

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