GeezerVison is showing github.com — feat(mcp): support client roots (#32230) · comio/opencode@f55a931
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: packages/opencode/src/mcp/index.ts +18-5Lines changed: 18 additions & 5 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 1 | 1 | import path from "node:path" | | 2 | +import { pathToFileURL } from "node:url" | 2 | 3 | import { LayerNode } from "@opencode-ai/core/effect/layer-node" | 3 | 4 | import { type Tool } from "ai" | 4 | 5 | import { ConfigV1 } from "@opencode-ai/core/v1/config/config" | @@ -9,6 +10,7 @@ import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js" | 9 | 10 | import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js" | 10 | 11 | import { UnauthorizedError } from "@modelcontextprotocol/sdk/client/auth.js" | 11 | 12 | import { | | 13 | + ListRootsRequestSchema, | 12 | 14 | type LoggingMessageNotification, | 13 | 15 | LoggingMessageNotificationSchema, | 14 | 16 | type Tool as MCPToolDef, | @@ -42,7 +44,7 @@ const CLIENT_OPTIONS = { | 42 | 44 | // https://github.com/anomalyco/opencode/issues/23066 | 43 | 45 | // elicitation: {}, | 44 | 46 | // https://github.com/anomalyco/opencode/issues/2308 | 45 | | - // roots: {}, | | 47 | + roots: {}, | 46 | 48 | // https://github.com/anomalyco/opencode/issues/28567 | 47 | 49 | // tasks: {}, | 48 | 50 | }, | @@ -82,6 +84,14 @@ export class NotFoundError extends Schema.TaggedErrorClass<NotFoundError>()("MCP | 82 | 84 |
| 83 | 85 | type MCPClient = Client | 84 | 86 |
| | 87 | +function createClient(directory: string) { | | 88 | + const client = new Client({ name: "opencode", version: InstallationVersion }, CLIENT_OPTIONS) | | 89 | + client.setRequestHandler(ListRootsRequestSchema, () => | | 90 | + Promise.resolve({ roots: [{ uri: pathToFileURL(directory).href }] }), | | 91 | + ) | | 92 | + return client | | 93 | +} | | 94 | + | 85 | 95 | const StatusConnected = Schema.Struct({ status: Schema.Literal("connected") }).annotate({ | 86 | 96 | identifier: "MCPStatusConnected", | 87 | 97 | }) | @@ -192,19 +202,21 @@ export const layer = Layer.effect( | 192 | 202 | * Connect a client via the given transport with resource safety: | 193 | 203 | * on failure the transport is closed; on success the caller owns it. | 194 | 204 | */ | 195 | | - const connectTransport = (transport: Transport, timeout: number) => | 196 | | - Effect.acquireUseRelease( | | 205 | + const connectTransport = Effect.fn("MCP.connectTransport")(function* (transport: Transport, timeout: number) { | | 206 | + const directory = yield* InstanceState.directory | | 207 | + return yield* Effect.acquireUseRelease( | 197 | 208 | Effect.succeed(transport), | 198 | 209 | (t) => | 199 | 210 | Effect.tryPromise({ | 200 | 211 | try: () => { | 201 | | - const client = new Client({ name: "opencode", version: InstallationVersion }, CLIENT_OPTIONS) | | 212 | + const client = createClient(directory) | 202 | 213 | return withTimeout(client.connect(t), timeout).then(() => client) | 203 | 214 | }, | 204 | 215 | catch: (e) => (e instanceof Error ? e : new Error(String(e))), | 205 | 216 | }), | 206 | 217 | (t, exit) => (Exit.isFailure(exit) ? Effect.tryPromise(() => t.close()).pipe(Effect.ignore) : Effect.void), | 207 | 218 | ) | | 219 | + }) | 208 | 220 |
| 209 | 221 | const DISABLED_RESULT: CreateResult = { status: { status: "disabled" } } | 210 | 222 |
| @@ -777,10 +789,11 @@ export const layer = Layer.effect( | 777 | 789 | authProvider, | 778 | 790 | requestInit: mcpConfig.headers ? { headers: mcpConfig.headers } : undefined, | 779 | 791 | }) | | 792 | + const directory = yield* InstanceState.directory | 780 | 793 |
| 781 | 794 | return yield* Effect.tryPromise({ | 782 | 795 | try: () => { | 783 | | - const client = new Client({ name: "opencode", version: InstallationVersion }, CLIENT_OPTIONS) | | 796 | + const client = createClient(directory) | 784 | 797 | return client | 785 | 798 | .connect(transport) | 786 | 799 | .then(() => ({ authorizationUrl: "", oauthState, client }) satisfies AuthResult) | |
Collapse file Copy file name to clipboardExpand all lines: packages/opencode/test/mcp/lifecycle.test.ts +34-2Lines changed: 34 additions & 2 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 1 | 1 | import path from "node:path" | | 2 | +import { pathToFileURL } from "node:url" | 2 | 3 | import { expect, mock, beforeEach } from "bun:test" | 3 | | -import { ToolListChangedNotificationSchema } from "@modelcontextprotocol/sdk/types.js" | | 4 | +import { ListRootsRequestSchema, ToolListChangedNotificationSchema } from "@modelcontextprotocol/sdk/types.js" | 4 | 5 | import { Cause, Effect, Exit } from "effect" | 5 | 6 | import type { MCP as MCPNS } from "../../src/mcp/index" | 6 | 7 | import { testEffect } from "../lib/effect" | @@ -38,6 +39,8 @@ interface MockClientState { | 38 | 39 | { resources: Array<{ name: string; uri: string; description?: string }>; nextCursor?: string } | 39 | 40 | > | 40 | 41 | closed: boolean | | 42 | + clientOptions?: { capabilities?: { roots?: { listChanged?: boolean } } } | | 43 | + requestHandlers: Map<unknown, (...args: any[]) => Promise<any>> | 41 | 44 | notificationHandlers: Map<unknown, (...args: any[]) => any> | 42 | 45 | } | 43 | 46 |
| @@ -75,6 +78,7 @@ function getOrCreateClientState(name?: string): MockClientState { | 75 | 78 | promptPages: {}, | 76 | 79 | resourcePages: {}, | 77 | 80 | closed: false, | | 81 | + requestHandlers: new Map(), | 78 | 82 | notificationHandlers: new Map(), | 79 | 83 | } | 80 | 84 | clientStates.set(key, state) | @@ -149,8 +153,10 @@ void mock.module("@modelcontextprotocol/sdk/client/index.js", () => ({ | 149 | 153 | _state!: MockClientState | 150 | 154 | transport: any | 151 | 155 |
| 152 | | - constructor(_opts: any) { | | 156 | + constructor(_info: any, options?: MockClientState["clientOptions"]) { | 153 | 157 | clientCreateCount++ | | 158 | + this._state = getOrCreateClientState(lastCreatedClientName) | | 159 | + this._state.clientOptions = options | 154 | 160 | } | 155 | 161 |
| 156 | 162 | async connect(transport: { start: () => Promise<void> }) { | @@ -160,6 +166,10 @@ void mock.module("@modelcontextprotocol/sdk/client/index.js", () => ({ | 160 | 166 | this._state = getOrCreateClientState(lastCreatedClientName) | 161 | 167 | } | 162 | 168 |
| | 169 | + setRequestHandler(schema: unknown, handler: (...args: any[]) => Promise<any>) { | | 170 | + this._state.requestHandlers.set(schema, handler) | | 171 | + } | | 172 | + | 163 | 173 | setNotificationHandler(schema: unknown, handler: (...args: any[]) => any) { | 164 | 174 | this._state?.notificationHandlers.set(schema, handler) | 165 | 175 | } | @@ -251,6 +261,28 @@ function statusName(status: Record<string, MCPNS.Status> | MCPNS.Status, server: | 251 | 261 | return status[server]?.status | 252 | 262 | } | 253 | 263 |
| | 264 | +it.instance( | | 265 | + "advertises and lists the instance directory as its root", | | 266 | + () => | | 267 | + MCP.Service.use((mcp: MCPNS.Interface) => | | 268 | + Effect.gen(function* () { | | 269 | + const { directory } = yield* TestInstance | | 270 | + lastCreatedClientName = "roots" | | 271 | + yield* mcp.add("roots", { type: "local", command: ["echo", "test"] }) | | 272 | + | | 273 | + const state = getOrCreateClientState("roots") | | 274 | + expect(state.clientOptions?.capabilities?.roots).toEqual({}) | | 275 | + expect(state.clientOptions?.capabilities?.roots?.listChanged).toBeUndefined() | | 276 | + | | 277 | + const handler = state.requestHandlers.get(ListRootsRequestSchema) | | 278 | + expect(handler).toBeDefined() | | 279 | + const result = yield* Effect.promise(() => handler?.() ?? Promise.reject(new Error("roots handler missing"))) | | 280 | + expect(result).toEqual({ roots: [{ uri: pathToFileURL(directory).href }] }) | | 281 | + }), | | 282 | + ), | | 283 | + { config: { mcp: {} } }, | | 284 | +) | | 285 | + | 254 | 286 | it.instance( | 255 | 287 | "local mcp cwd resolves relative paths against instance directory", | 256 | 288 | () => | |
Collapse file Copy file name to clipboardExpand all lines: packages/opencode/test/mcp/oauth-auto-connect.test.ts +2Lines changed: 2 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -87,6 +87,8 @@ void mock.module("@modelcontextprotocol/sdk/client/sse.js", () => ({ | 87 | 87 | // Mock the MCP SDK Client | 88 | 88 | void mock.module("@modelcontextprotocol/sdk/client/index.js", () => ({ | 89 | 89 | Client: class MockClient { | | 90 | + setRequestHandler() {} | | 91 | + | 90 | 92 | async connect(transport: { start: () => Promise<void> }) { | 91 | 93 | await transport.start() | 92 | 94 | } | |
Collapse file Copy file name to clipboardExpand all lines: packages/opencode/test/mcp/oauth-browser.test.ts +2Lines changed: 2 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -89,6 +89,8 @@ void mock.module("@modelcontextprotocol/sdk/client/sse.js", () => ({ | 89 | 89 | // Mock the MCP SDK Client to trigger OAuth flow | 90 | 90 | void mock.module("@modelcontextprotocol/sdk/client/index.js", () => ({ | 91 | 91 | Client: class MockClient { | | 92 | + setRequestHandler() {} | | 93 | + | 92 | 94 | async connect(transport: { start: () => Promise<void> }) { | 93 | 95 | await transport.start() | 94 | 96 | } | |
|