Skip to content

Commit 32ee528

Browse files
fix(ai): share McpServer state with wrapped services (#11274)
Co-authored-by: Rhys Sullivan <39114868+RhysSullivan@users.noreply.github.com>
1 parent 27b090b commit 32ee528

3 files changed

Lines changed: 104 additions & 49 deletions

File tree

‎.changeset/mcp-server-wrappers.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"effect": patch
3+
---
4+
5+
`McpServer` wrappers made with object spread or `Object.create` now support global middleware, skills, and transports. Override the new `addToolSource` service member to intercept tool source registrations.

‎packages/effect/src/ai/McpServer.ts‎

Lines changed: 63 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -113,14 +113,18 @@ interface QueuedServerNotification {
113113
readonly requestLiveness?: { active: boolean } | undefined
114114
}
115115

116-
const internalState = new WeakMap<object, {
116+
// An enumerable symbol lets object spread and `Object.create` wrappers share state.
117+
const stateKey = Symbol()
118+
interface ServerState {
117119
readonly core: McpCore.McpCore
118120
// Registers a skill's own file, skipping the check that reserves it for the skill.
119121
readonly addSkillFile: McpServer["Service"]["addResource"]
120122
readonly notifications: Queue.Dequeue<QueuedServerNotification>
121123
readonly notificationDelivery: { consumers: number; listChangeRevision: number; requestEndpoints: number }
122124
readonly globalMiddleware: Array<middleware.Fn<any, any, any>>
123-
}>()
125+
}
126+
type WithState = McpServer["Service"] & { [stateKey]: ServerState }
127+
const serverState = (server: McpServer["Service"]): ServerState => (server as WithState)[stateKey]
124128

125129
// Request-scoped HTTP servers deliver a request's own notifications through
126130
// that request's server instead of the shared notification queue.
@@ -743,7 +747,7 @@ class MiddlewareImpl {
743747
yield* Effect.context<never>(),
744748
contextKey as any
745749
)!
746-
const { globalMiddleware } = internalState.get(yield* McpServer)!
750+
const { globalMiddleware } = serverState(yield* McpServer)
747751
yield* Effect.acquireRelease(
748752
Effect.sync(() => {
749753
globalMiddleware.push(...stack)
@@ -1046,6 +1050,10 @@ const toolOutcome = (
10461050
* Handlers use this service to register capabilities and resolve incoming MCP
10471051
* requests.
10481052
*
1053+
* Wrap this service with object spread or `Object.create` to override `addTool`
1054+
* or `addToolSource`. Toolkit and tool source registration call these members.
1055+
* Global middleware, skills, and transports use the wrapped server's shared state.
1056+
*
10491057
* @stability unstable
10501058
* @category services
10511059
* @since 4.0.0
@@ -1072,6 +1080,11 @@ export class McpServer extends Context.Service<McpServer, {
10721080
McpRequestContext
10731081
>
10741082
}) => Effect.Effect<void>
1083+
readonly addToolSource: (
1084+
options: ToolSourceOptions<McpRequestContext, McpRequestContext> & {
1085+
readonly services?: Context.Context<never> | undefined
1086+
}
1087+
) => Effect.Effect<void>
10751088
readonly callTool: (
10761089
requests: typeof CallTool.payloadSchema.Type
10771090
) => Effect.Effect<CallToolResult, McpErrorBase | InternalError | InvalidParams, McpServerClient>
@@ -1282,7 +1295,7 @@ export class McpServer extends Context.Service<McpServer, {
12821295
})
12831296
return notifications.client["notifications/resources/list_changed"]({})
12841297
})
1285-
const service = McpServer.of({
1298+
const service: WithState = {
12861299
notifications: notifications.client,
12871300
notifyElicitationComplete: ({ clientId, elicitationId }) =>
12881301
withoutSharedConsumer() ? Effect.void : Deferred.make<void>().pipe(
@@ -1327,6 +1340,32 @@ export class McpServer extends Context.Service<McpServer, {
13271340
})
13281341
yield* notifications.client["notifications/tools/list_changed"]({})
13291342
}),
1343+
addToolSource: Effect.fnUntraced(function*(options) {
1344+
const { invoke, invokeList, visible } = makeInvoke(options.services, globalMiddleware)
1345+
yield* internalCore.tools.registerSource({
1346+
owns: options.owns ?? (() => true),
1347+
list: (invocation) =>
1348+
invokeList(options.list, invocation).pipe(
1349+
Effect.flatMap(Effect.filter((tool) => visible("tools/list", tool.name)(invocation))),
1350+
Effect.map(Arr.map(withAnnotationTitle))
1351+
),
1352+
handle: (call, invocation) =>
1353+
toolOutcome(
1354+
invoke(
1355+
Effect.catchTag(
1356+
Effect.suspend(() => options.call(call.name, call.arguments ?? {})),
1357+
"NoSuchElementError",
1358+
() => failHidden
1359+
),
1360+
invocation,
1361+
{ method: "tools/call", target: call.name, payload: call }
1362+
),
1363+
call.name,
1364+
invocation
1365+
)
1366+
})
1367+
yield* notifications.client["notifications/tools/list_changed"]({})
1368+
}),
13301369
callTool: Effect.fnUntraced(function*(request) {
13311370
const client = yield* McpServerClient
13321371
const result = yield* internalCore.tools.call(
@@ -1508,16 +1547,16 @@ export class McpServer extends Context.Service<McpServer, {
15081547
hasMore: result.hasMore
15091548
}
15101549
}
1511-
})
1512-
})
1513-
internalState.set(service, {
1514-
core: internalCore,
1515-
addSkillFile: (options) => addResource(options, false),
1516-
notifications: notificationsQueue,
1517-
notificationDelivery,
1518-
globalMiddleware
1519-
})
1520-
return service
1550+
}),
1551+
[stateKey]: {
1552+
core: internalCore,
1553+
addSkillFile: (options) => addResource(options, false),
1554+
notifications: notificationsQueue,
1555+
notificationDelivery,
1556+
globalMiddleware
1557+
}
1558+
}
1559+
return McpServer.of(service)
15211560
})
15221561

15231562
/**
@@ -1965,7 +2004,7 @@ const runWithRuntime = Effect.fnUntraced(function*(
19652004
let writeFromClient!: (clientId: number, message: RpcMessage.FromClientEncoded) => Effect.Effect<void>
19662005
// Set when stdio stops, before RpcServer interrupts handlers; their interrupts are then treated as cancellations.
19672006
let stdioStopped = false
1968-
const { core, notificationDelivery, notifications } = internalState.get(server)!
2007+
const { core, notificationDelivery, notifications } = serverState(server)
19692008
const handlers = requestScoped?.handlers ?? (yield* runtime.installHandlers({
19702009
core,
19712010
subscribeServerNotifications: PubSub.subscribe(serverNotifications),
@@ -2990,7 +3029,7 @@ export const layerHttpRequestScoped = <
29903029
}
29913030
const serverOptions = { ...options, cacheHints: yield* normalizeCacheHints(options.cacheHints) }
29923031
const server = yield* McpServer
2993-
const { core, notificationDelivery } = internalState.get(server)!
3032+
const { core, notificationDelivery } = serverState(server)
29943033
// Subscriptions are disabled, so handlers hold no per-request state and
29953034
// read registrations from the shared core on every call. Request services
29963035
// still take precedence over the layer context captured here.
@@ -3811,32 +3850,15 @@ export const registerToolSource = <RList = never, RCall = never>(
38113850
options: ToolSourceOptions<RList, RCall>
38123851
): Effect.Effect<void, never, ToolSourceRequirements<RList | RCall>> =>
38133852
Effect.gen(function*() {
3853+
const services = yield* Effect.context<never>()
38143854
const registry = yield* McpServer
3815-
const { core, globalMiddleware } = internalState.get(registry)!
3816-
const { invoke, invokeList, visible } = makeInvoke(yield* Effect.context<never>(), globalMiddleware)
3817-
yield* core.tools.registerSource({
3818-
owns: options.owns ?? (() => true),
3819-
list: (invocation) =>
3820-
invokeList(options.list, invocation).pipe(
3821-
Effect.flatMap(Effect.filter((tool) => visible("tools/list", tool.name)(invocation))),
3822-
Effect.map(Arr.map(withAnnotationTitle))
3823-
),
3824-
handle: (call, invocation) =>
3825-
toolOutcome(
3826-
invoke(
3827-
Effect.catchTag(
3828-
Effect.suspend(() => options.call(call.name, call.arguments ?? {})),
3829-
"NoSuchElementError",
3830-
() => failHidden
3831-
),
3832-
invocation,
3833-
{ method: "tools/call", target: call.name, payload: call }
3834-
),
3835-
call.name,
3836-
invocation
3837-
)
3855+
// Preserve prototype methods and their original receiver.
3856+
yield* registry.addToolSource({
3857+
list: options.list as ToolSourceOptions<any>["list"],
3858+
call: (name, payload) => options.call(name, payload) as ReturnType<ToolSourceOptions<any, any>["call"]>,
3859+
owns: options.owns && ((name) => options.owns!(name)),
3860+
services
38383861
})
3839-
yield* registry.notifications["notifications/tools/list_changed"]({})
38403862
})
38413863

38423864
/**
@@ -4295,7 +4317,7 @@ const registerSkillFiles: (options: SkillOptions) => Effect.Effect<void, Cause.I
42954317
)
42964318

42974319
const registry = yield* McpServer
4298-
const { addSkillFile, core, globalMiddleware } = internalState.get(registry)!
4320+
const { addSkillFile, core, globalMiddleware } = serverState(registry)
42994321
const services = yield* Effect.context<never>()
43004322
const annotations = options.annotations ?? Context.empty()
43014323
const { invoke, visible } = makeInvoke(services, globalMiddleware)

‎packages/effect/test/ai/McpServer/McpServer.test.ts‎

Lines changed: 36 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4506,6 +4506,18 @@ describe("McpServer", () => {
45064506
const Observe = McpServer.middleware()((effect) =>
45074507
Effect.tapError(effect, (error) => Effect.sync(() => failureCodes.push(error.code)))
45084508
)
4509+
// A class instance checks that registration keeps prototype methods.
4510+
class FirstSource implements McpServer.ToolSourceOptions {
4511+
readonly list = Effect.suspend(() => Effect.as(duringList, dynamicNames.map(descriptor)))
4512+
owns(name: string) {
4513+
return name !== "Logs"
4514+
}
4515+
call(name: string, args: unknown) {
4516+
return name === "Unknown"
4517+
? Effect.fail(new Cause.NoSuchElementError())
4518+
: Effect.succeed(textResult(`first:${name}:${JSON.stringify(args)}`))
4519+
}
4520+
}
45094521
const registrations = Layer.mergeAll(
45104522
McpServer.toolkit(StaticVisible).pipe(
45114523
Layer.provide(StaticVisible.toLayer({ Search: () => Effect.succeed("static") }))
@@ -4514,14 +4526,7 @@ describe("McpServer", () => {
45144526
Layer.provide(McpServer.visibility(() => Effect.succeed(false)).layer),
45154527
Layer.provide(StaticHidden.toLayer({ HiddenStatic: () => Effect.succeed("hidden") }))
45164528
),
4517-
Layer.effectDiscard(McpServer.registerToolSource({
4518-
owns: (name) => name !== "Logs",
4519-
list: Effect.suspend(() => Effect.as(duringList, dynamicNames.map(descriptor))),
4520-
call: (name, args) =>
4521-
name === "Unknown"
4522-
? Effect.fail(new Cause.NoSuchElementError())
4523-
: Effect.succeed(textResult(`first:${name}:${JSON.stringify(args)}`))
4524-
})).pipe(Layer.provide(Observe.layer)),
4529+
Layer.effectDiscard(McpServer.registerToolSource(new FirstSource())).pipe(Layer.provide(Observe.layer)),
45254530
McpServer.toolSource({
45264531
list: Effect.succeed(["Status", "Logs"].map(descriptor)),
45274532
call: (name, args) => Effect.succeed(textResult(`second:${name}:${JSON.stringify(args)}`))
@@ -4640,4 +4645,27 @@ describe("McpServer", () => {
46404645
)
46414646
}))
46424647
})
4648+
4649+
it.effect("wrapped services share server state and intercept tool sources", () =>
4650+
Effect.gen(function*() {
4651+
const server = yield* McpServer.McpServer.make
4652+
let intercepted = 0
4653+
const addToolSource: McpServer.McpServer["Service"]["addToolSource"] = (options) => {
4654+
intercepted++
4655+
return server.addToolSource(options)
4656+
}
4657+
const registrations = Layer.mergeAll(
4658+
McpServer.middleware()((effect) => effect).layerGlobal,
4659+
McpServer.toolSource({ list: Effect.succeed([]), call: () => Effect.die("unused") })
4660+
)
4661+
for (
4662+
const wrapped of [
4663+
{ ...server, addToolSource },
4664+
Object.create(server, { addToolSource: { value: addToolSource } })
4665+
]
4666+
) {
4667+
yield* Layer.build(registrations).pipe(Effect.provideService(McpServer.McpServer, wrapped))
4668+
}
4669+
assert.strictEqual(intercepted, 2)
4670+
}))
46434671
})

0 commit comments

Comments
 (0)