clanka 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/README.md +49 -0
  2. package/dist/Acp.d.ts +1 -1
  3. package/dist/Acp.d.ts.map +1 -1
  4. package/dist/Acp.js +112 -7
  5. package/dist/Acp.js.map +1 -1
  6. package/dist/Acp.test.js +178 -0
  7. package/dist/Acp.test.js.map +1 -1
  8. package/dist/Agent.d.ts.map +1 -1
  9. package/dist/Agent.js +26 -8
  10. package/dist/Agent.js.map +1 -1
  11. package/dist/AgentExecutor.js +15 -1
  12. package/dist/AgentExecutor.js.map +1 -1
  13. package/dist/AgentTools.d.ts +7 -0
  14. package/dist/AgentTools.d.ts.map +1 -1
  15. package/dist/AgentTools.js +7 -0
  16. package/dist/AgentTools.js.map +1 -1
  17. package/dist/McpConfig.d.ts +36 -0
  18. package/dist/McpConfig.d.ts.map +1 -0
  19. package/dist/McpConfig.js +182 -0
  20. package/dist/McpConfig.js.map +1 -0
  21. package/dist/McpConfig.test.d.ts +2 -0
  22. package/dist/McpConfig.test.d.ts.map +1 -0
  23. package/dist/McpConfig.test.js +163 -0
  24. package/dist/McpConfig.test.js.map +1 -0
  25. package/dist/McpServers.d.ts +176 -0
  26. package/dist/McpServers.d.ts.map +1 -0
  27. package/dist/McpServers.js +707 -0
  28. package/dist/McpServers.js.map +1 -0
  29. package/dist/McpServers.test.d.ts +2 -0
  30. package/dist/McpServers.test.d.ts.map +1 -0
  31. package/dist/McpServers.test.js +717 -0
  32. package/dist/McpServers.test.js.map +1 -0
  33. package/dist/TypeBuilder.d.ts +9 -0
  34. package/dist/TypeBuilder.d.ts.map +1 -1
  35. package/dist/TypeBuilder.js +24 -11
  36. package/dist/TypeBuilder.js.map +1 -1
  37. package/dist/TypeBuilder.test.js +33 -0
  38. package/dist/TypeBuilder.test.js.map +1 -1
  39. package/dist/bin/{Effect-zUBunSAW.mjs → Effect-DuThyCJ1.mjs} +87 -9
  40. package/dist/bin/Effect-DuThyCJ1.mjs.map +1 -0
  41. package/dist/bin/McpClient-CIiPyMDJ.mjs +36 -0
  42. package/dist/bin/McpClient-CIiPyMDJ.mjs.map +1 -0
  43. package/dist/bin/{OutputFormatter-BPdc6RmH.mjs → OutputFormatter-BvIjvUmT.mjs} +3 -3
  44. package/dist/bin/{OutputFormatter-BPdc6RmH.mjs.map → OutputFormatter-BvIjvUmT.mjs.map} +1 -1
  45. package/dist/bin/{Schema-C2Y2y3tU.mjs → Schema-DcXUXpRg.mjs} +831 -35
  46. package/dist/bin/Schema-DcXUXpRg.mjs.map +1 -0
  47. package/dist/bin/{SemanticSearch-BKZxP19F.mjs → SemanticSearch-CdGA4CIC.mjs} +5 -5
  48. package/dist/bin/{SemanticSearch-BKZxP19F.mjs.map → SemanticSearch-CdGA4CIC.mjs.map} +1 -1
  49. package/dist/bin/{Stream-BvmRbTMu.mjs → Stream-I9SRMlLj.mjs} +20 -22
  50. package/dist/bin/Stream-I9SRMlLj.mjs.map +1 -0
  51. package/dist/bin/cli.mjs +17642 -802
  52. package/dist/bin/cli.mjs.map +1 -1
  53. package/dist/bin/{index.min-DbZbUHX3.mjs → index.min-Bkz7vIWv.mjs} +5 -5
  54. package/dist/bin/{index.min-DbZbUHX3.mjs.map → index.min-Bkz7vIWv.mjs.map} +1 -1
  55. package/dist/bin/rolldown-runtime-zY4HT0JA.mjs +30 -0
  56. package/dist/bin/{turndown.cjs-DK29wZw3.mjs → turndown.cjs-LntFxFyd.mjs} +2 -2
  57. package/dist/bin/{turndown.cjs-DK29wZw3.mjs.map → turndown.cjs-LntFxFyd.mjs.map} +1 -1
  58. package/dist/cli.js +24 -2
  59. package/dist/cli.js.map +1 -1
  60. package/dist/fixtures/McpFakeServer.d.ts +47 -0
  61. package/dist/fixtures/McpFakeServer.d.ts.map +1 -0
  62. package/dist/fixtures/McpFakeServer.js +112 -0
  63. package/dist/fixtures/McpFakeServer.js.map +1 -0
  64. package/dist/fixtures/McpStdioServer.d.ts +2 -0
  65. package/dist/fixtures/McpStdioServer.d.ts.map +1 -0
  66. package/dist/fixtures/McpStdioServer.js +53 -0
  67. package/dist/fixtures/McpStdioServer.js.map +1 -0
  68. package/dist/index.d.ts +4 -0
  69. package/dist/index.d.ts.map +1 -1
  70. package/dist/index.js +4 -0
  71. package/dist/index.js.map +1 -1
  72. package/package.json +1 -1
  73. package/src/Acp.test.ts +242 -0
  74. package/src/Acp.ts +141 -5
  75. package/src/Agent.ts +38 -10
  76. package/src/AgentExecutor.ts +14 -1
  77. package/src/AgentTools.ts +8 -0
  78. package/src/McpConfig.test.ts +238 -0
  79. package/src/McpConfig.ts +255 -0
  80. package/src/McpServers.test.ts +1050 -0
  81. package/src/McpServers.ts +1072 -0
  82. package/src/TypeBuilder.test.ts +70 -0
  83. package/src/TypeBuilder.ts +41 -14
  84. package/src/cli.ts +46 -0
  85. package/src/fixtures/McpFakeServer.ts +162 -0
  86. package/src/fixtures/McpStdioServer.ts +60 -0
  87. package/src/index.ts +5 -0
  88. package/dist/bin/Effect-zUBunSAW.mjs.map +0 -1
  89. package/dist/bin/McpClient-CnP2P7c9.mjs +0 -14179
  90. package/dist/bin/McpClient-CnP2P7c9.mjs.map +0 -1
  91. package/dist/bin/Schema-C2Y2y3tU.mjs.map +0 -1
  92. package/dist/bin/Stream-BvmRbTMu.mjs.map +0 -1
@@ -0,0 +1,1050 @@
1
+ import { assert, describe, it } from "@effect/vitest"
2
+ import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer"
3
+ import * as NodeServices from "@effect/platform-node/NodeServices"
4
+ import * as Duration from "effect/Duration"
5
+ import * as Effect from "effect/Effect"
6
+ import * as FileSystem from "effect/FileSystem"
7
+ import * as FetchHttpClient from "effect/http/FetchHttpClient"
8
+ import * as HttpServer from "effect/http/HttpServer"
9
+ import * as Layer from "effect/Layer"
10
+ import * as Path from "effect/Path"
11
+ import * as Redacted from "effect/Redacted"
12
+ import * as Schedule from "effect/Schedule"
13
+ import * as Schema from "effect/Schema"
14
+ import * as Stream from "effect/Stream"
15
+ import * as LanguageModel from "effect/ai/LanguageModel"
16
+ import * as Model from "effect/ai/Model"
17
+ import type * as Prompt from "effect/ai/Prompt"
18
+ import type * as Response from "effect/ai/Response"
19
+ import * as Tool from "effect/ai/Tool"
20
+ import * as Toolkit from "effect/ai/Toolkit"
21
+ import * as RpcClient from "effect/rpc/RpcClient"
22
+ import * as RpcSerialization from "effect/rpc/RpcSerialization"
23
+ import * as RpcServer from "effect/rpc/RpcServer"
24
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"
25
+ import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"
26
+ import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"
27
+ import * as Agent from "./Agent.ts"
28
+ import * as AgentExecutor from "./AgentExecutor.ts"
29
+ import * as McpServers from "./McpServers.ts"
30
+ import {
31
+ type FakeTool,
32
+ listenHttp,
33
+ makeFakeServer,
34
+ text,
35
+ } from "./fixtures/McpFakeServer.ts"
36
+ import { tinyPng } from "./fixtures/TestImages.ts"
37
+
38
+ // =============================================================================
39
+ // MCP servers as seen by the model.
40
+ //
41
+ // The library is observed where the model meets it: the system prompt, the
42
+ // `mcp.<server>.<tool>` functions and `searchTools` in a script, plus the
43
+ // service's per-server status. Servers are fake SDK servers over
44
+ // `InMemoryTransport`, handed to `McpServers.layerTransports`; one test each
45
+ // runs the stdio fixture and a loopback HTTP server through
46
+ // `McpServers.layer`.
47
+ //
48
+ // The model is scripted: each call answers with one `execute` script, routed
49
+ // by role, as in AgentSubagents.test.ts. A sub-agent's first user message
50
+ // carries "TASK-CHILD".
51
+ // =============================================================================
52
+
53
+ type Mode = "local" | "rpc"
54
+
55
+ const modes: ReadonlyArray<Mode> = ["local", "rpc"]
56
+
57
+ type Role = "root" | "child"
58
+
59
+ interface Call {
60
+ readonly role: Role
61
+ readonly index: number
62
+ readonly prompt: Prompt.Prompt
63
+ }
64
+
65
+ interface ExecutorOptions {
66
+ readonly tools?: Toolkit.Any | undefined
67
+ }
68
+
69
+ const localExecutor = (options: ExecutorOptions) =>
70
+ Layer.unwrap(
71
+ Effect.gen(function* () {
72
+ const fs = yield* FileSystem.FileSystem
73
+ const directory = yield* fs.makeTempDirectoryScoped()
74
+ return AgentExecutor.layerLocal({ directory, ...options })
75
+ }),
76
+ ).pipe(
77
+ Layer.provide(Layer.mergeAll(NodeServices.layer, FetchHttpClient.layer)),
78
+ )
79
+
80
+ const rpcExecutor = (options: ExecutorOptions) =>
81
+ Layer.unwrap(
82
+ Effect.gen(function* () {
83
+ const fs = yield* FileSystem.FileSystem
84
+ const directory = yield* fs.makeTempDirectoryScoped()
85
+ const { protocol, httpEffect } =
86
+ yield* RpcServer.makeProtocolWithHttpEffect()
87
+ yield* Layer.build(
88
+ AgentExecutor.layerRpcServer({ directory, ...options }).pipe(
89
+ Layer.provide(Layer.succeed(RpcServer.Protocol, protocol)),
90
+ ),
91
+ )
92
+ yield* HttpServer.serveEffect(httpEffect)
93
+ return AgentExecutor.layerRpc.pipe(
94
+ Layer.provide(RpcClient.layerProtocolHttp({ url: "" })),
95
+ )
96
+ }),
97
+ ).pipe(
98
+ Layer.provide(
99
+ Layer.mergeAll(
100
+ RpcSerialization.layerNdjson,
101
+ NodeHttpServer.layerTest,
102
+ NodeServices.layer,
103
+ ),
104
+ ),
105
+ )
106
+
107
+ const executorLayer = (mode: Mode, options: ExecutorOptions = {}) =>
108
+ mode === "local" ? localExecutor(options) : rpcExecutor(options)
109
+
110
+ const messageText = (message: Prompt.Message): string =>
111
+ typeof message.content === "string"
112
+ ? message.content
113
+ : message.content
114
+ .map((part) => (part.type === "text" ? part.text : ""))
115
+ .join("")
116
+
117
+ const systemText = (prompt: Prompt.Prompt): string =>
118
+ prompt.content
119
+ .filter((message) => message.role === "system")
120
+ .map(messageText)
121
+ .join("\n")
122
+
123
+ const firstUserText = (prompt: Prompt.Prompt): string => {
124
+ const message = prompt.content.find((message) => message.role === "user")
125
+ return message ? messageText(message) : ""
126
+ }
127
+
128
+ const lastToolResult = (prompt: Prompt.Prompt): string => {
129
+ const message = prompt.content.findLast((message) => message.role === "tool")
130
+ if (message === undefined) return ""
131
+ return message.content
132
+ .map((part) => (part.type === "tool-result" ? String(part.result) : ""))
133
+ .join("")
134
+ }
135
+
136
+ const hasPngAttachment = (prompt: Prompt.Prompt): boolean =>
137
+ prompt.content.some(
138
+ (message) =>
139
+ message.role === "user" &&
140
+ typeof message.content !== "string" &&
141
+ message.content.some(
142
+ (part) => part.type === "file" && part.mediaType === "image/png",
143
+ ),
144
+ )
145
+
146
+ const toolCall = (call: Call, script: string): Response.StreamPartEncoded => ({
147
+ type: "tool-call",
148
+ id: `call-${call.role}-${call.index}`,
149
+ name: "execute",
150
+ params: { script },
151
+ })
152
+
153
+ /**
154
+ * Runs the Agent with whatever `McpServers` the surrounding context provides.
155
+ * A string script must end with `taskComplete`; a function answers every
156
+ * model call.
157
+ */
158
+ const runAgent = <LoopTools extends Toolkit.Any = never>(options: {
159
+ readonly mode?: Mode | undefined
160
+ readonly agent?: Agent.Options<LoopTools> | undefined
161
+ readonly script: string | ((call: Call) => string)
162
+ }) =>
163
+ Effect.gen(function* () {
164
+ const calls: Array<Call> = []
165
+ const counts: Record<Role, number> = { root: 0, child: 0 }
166
+ const languageModel = yield* LanguageModel.make({
167
+ generateText: () => Effect.die("unexpected generateText call"),
168
+ streamText: (providerOptions) => {
169
+ const role: Role = firstUserText(providerOptions.prompt).includes(
170
+ "TASK-CHILD",
171
+ )
172
+ ? "child"
173
+ : "root"
174
+ const call: Call = {
175
+ role,
176
+ index: counts[role]++,
177
+ prompt: providerOptions.prompt,
178
+ }
179
+ calls.push(call)
180
+ if (typeof options.script !== "string") {
181
+ return Stream.make(toolCall(call, options.script(call)))
182
+ }
183
+ return call.index === 0
184
+ ? Stream.make(toolCall(call, options.script))
185
+ : Stream.die(
186
+ `the script did not call taskComplete: ${lastToolResult(call.prompt)}`,
187
+ )
188
+ },
189
+ })
190
+ const modelLayer = Layer.mergeAll(
191
+ Layer.succeed(LanguageModel.LanguageModel, languageModel),
192
+ Layer.succeed(Model.ProviderName, "test-provider"),
193
+ Layer.succeed(Model.ModelName, "test-model"),
194
+ )
195
+ const agent = yield* Agent.makeWith(options.agent ?? {})
196
+ const summary = yield* agent.send({ prompt: "hello" }).pipe(
197
+ Effect.flatMap(Stream.runDrain),
198
+ Effect.as(""),
199
+ Effect.catchTag("AgentFinished", (finished) =>
200
+ Effect.succeed(finished.summary),
201
+ ),
202
+ Effect.provide(modelLayer),
203
+ )
204
+ return { system: systemText(calls[0]!.prompt), summary, calls }
205
+ }).pipe(
206
+ Effect.scoped,
207
+ Effect.provide(executorLayer(options.mode ?? "local")),
208
+ Effect.timeout("4 seconds"),
209
+ )
210
+
211
+ // Turns a rejection into a value, so one script can report several calls.
212
+ const attempt = `const attempt = (call) => call.then((value) => value, (error) => "ERR " + error.message)
213
+ `
214
+
215
+ /**
216
+ * A fake server reached over `InMemoryTransport`. Every connect builds a new
217
+ * server, so `connections` counts the connections the library opened.
218
+ */
219
+ const fake = (options: Parameters<typeof makeFakeServer>[0]) => {
220
+ const state = {
221
+ connections: 0,
222
+ transport: (): Transport => {
223
+ state.connections++
224
+ const [client, server] = InMemoryTransport.createLinkedPair()
225
+ void makeFakeServer(options).connect(server)
226
+ return client
227
+ },
228
+ }
229
+ return state
230
+ }
231
+
232
+ // A server that cannot be reached.
233
+ const refused = (): Transport => ({
234
+ start: () => Promise.reject(new Error("connection refused: boom")),
235
+ send: () => Promise.resolve(),
236
+ close: () => Promise.resolve(),
237
+ })
238
+
239
+ // A server that never answers `initialize`.
240
+ const silent = (): Transport => InMemoryTransport.createLinkedPair()[0]
241
+
242
+ const named = (...names: ReadonlyArray<string>): Array<FakeTool> =>
243
+ names.map((name) => ({ name, call: () => text(name) }))
244
+
245
+ const currentStatus = Effect.gen(function* () {
246
+ const servers = yield* McpServers.McpServers
247
+ return yield* servers.status
248
+ })
249
+
250
+ const failure = (
251
+ status: Effect.Success<typeof currentStatus>,
252
+ name: string,
253
+ ): string => {
254
+ const server = status[name]
255
+ if (server?._tag !== "Failed") {
256
+ return assert.fail(`expected ${name} to have failed`)
257
+ }
258
+ return server.error
259
+ }
260
+
261
+ const count = (text: string, pattern: RegExp): number =>
262
+ (text.match(pattern) ?? []).length
263
+
264
+ const isRunning = (pid: number): boolean => {
265
+ try {
266
+ process.kill(pid, 0)
267
+ return true
268
+ } catch {
269
+ return false
270
+ }
271
+ }
272
+
273
+ const exited = (pid: number) =>
274
+ Effect.sync(() => isRunning(pid)).pipe(
275
+ Effect.repeat({
276
+ while: (running) => running,
277
+ schedule: Schedule.spaced("50 millis"),
278
+ }),
279
+ Effect.timeout("3 seconds"),
280
+ )
281
+
282
+ const fixture = (path: Path.Path) =>
283
+ path.join(import.meta.dirname, "fixtures", "McpStdioServer.ts")
284
+
285
+ // Builds an Agent, returning "built" or the defect that stopped it.
286
+ const build = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
287
+ effect.pipe(
288
+ Effect.as("built"),
289
+ Effect.scoped,
290
+ Effect.catchDefect((defect) => Effect.succeed(String(defect))),
291
+ )
292
+
293
+ // A session the server ended is terminal, whichever layer built the
294
+ // transport.
295
+ const endedSession = (
296
+ layer: (url: string) => Layer.Layer<McpServers.McpServers>,
297
+ ) =>
298
+ Effect.gen(function* () {
299
+ // The `end` tool ends the session it is called in.
300
+ let endSession: (() => void) | undefined
301
+ const remote = yield* Effect.acquireRelease(
302
+ Effect.promise(() =>
303
+ listenHttp(
304
+ makeFakeServer({
305
+ tools: [
306
+ { name: "ping", call: () => text("pong") },
307
+ {
308
+ name: "end",
309
+ call: () => {
310
+ endSession?.()
311
+ return text("ended")
312
+ },
313
+ },
314
+ ],
315
+ }),
316
+ ),
317
+ ),
318
+ (remote) => Effect.promise(remote.close),
319
+ )
320
+ endSession = remote.endSession
321
+ const { summary, status } = yield* Effect.gen(function* () {
322
+ const { summary } = yield* runAgent({
323
+ script: `${attempt}
324
+ await mcp.remote.end({})
325
+ const first = await attempt(mcp.remote.ping({}))
326
+ await taskComplete(JSON.stringify({ first, second: await attempt(mcp.remote.ping({})) }))`,
327
+ })
328
+ return { summary, status: yield* currentStatus }
329
+ }).pipe(Effect.provide(layer(remote.url)))
330
+ const { first, second } = JSON.parse(summary)
331
+ // The 404 ends the session; the next call is rejected locally.
332
+ assert.match(first, /^ERR mcp\.remote\.ping: /)
333
+ assert.match(
334
+ second,
335
+ /^ERR mcp\.remote\.ping: MCP server "remote" is not connected: /,
336
+ )
337
+ failure(status, "remote")
338
+ assert.deepStrictEqual(
339
+ remote.afterEnd.filter((request) => request.startsWith("POST")),
340
+ ["POST tools/call"],
341
+ )
342
+ }).pipe(Effect.scoped)
343
+
344
+ // --- lifecycle and prompt ----------------------------------------------------
345
+
346
+ describe("McpServers", () => {
347
+ it.live(
348
+ "a failed server never stops the Agent and is listed in the prompt",
349
+ () => {
350
+ const github = fake({
351
+ instructions: `GITHUB-INSTRUCTIONS ${"x".repeat(3000)} INSTRUCTIONS-TAIL`,
352
+ tools: [
353
+ {
354
+ name: "create_issue",
355
+ description: "PRIVATE-DESCRIPTION",
356
+ call: () => text("created"),
357
+ },
358
+ ],
359
+ })
360
+ return Effect.gen(function* () {
361
+ const { system, summary } = yield* runAgent({
362
+ script:
363
+ "await taskComplete([typeof mcp.github.create_issue, typeof searchTools].join())",
364
+ })
365
+ const status = yield* currentStatus
366
+ assert.strictEqual(summary, "function,function")
367
+ assert.strictEqual(github.connections, 1)
368
+ assert.strictEqual(status["github"]?._tag, "Connected")
369
+ assert.include(failure(status, "broken"), "boom")
370
+ failure(status, "slow")
371
+
372
+ // Instructions are capped; failed servers get one line with the reason.
373
+ assert.include(system, "GITHUB-INSTRUCTIONS")
374
+ assert.notInclude(system, "INSTRUCTIONS-TAIL")
375
+ assert.match(system, /broken.*boom/)
376
+ assert.include(system, "slow")
377
+ assert.include(system, "declare function searchTools(")
378
+ // Each connected server shows the call that lists its tools.
379
+ assert.include(system, 'searchTools({ server: "github" })')
380
+ assert.notInclude(system, 'searchTools({ server: "broken" })')
381
+ // Tool types are only returned by `searchTools`.
382
+ assert.notInclude(system, "PRIVATE-DESCRIPTION")
383
+ assert.notInclude(system, "declare namespace mcp")
384
+ }).pipe(
385
+ Effect.provide(
386
+ McpServers.layerTransports({
387
+ github: { transport: github.transport },
388
+ broken: { transport: refused },
389
+ slow: { transport: silent, connectTimeout: Duration.millis(50) },
390
+ }),
391
+ ),
392
+ )
393
+ },
394
+ )
395
+
396
+ it.live("without a connected server nothing MCP is bound or declared", () =>
397
+ Effect.gen(function* () {
398
+ const script =
399
+ "await taskComplete([typeof mcp, typeof searchTools].join())"
400
+
401
+ const without = yield* runAgent({ script })
402
+ assert.strictEqual(without.summary, "undefined,undefined")
403
+ assert.notMatch(without.system, /searchTools|MCP|\bmcp\b/)
404
+
405
+ const allFailed = yield* runAgent({ script }).pipe(
406
+ Effect.provide(
407
+ McpServers.layerTransports({ broken: { transport: refused } }),
408
+ ),
409
+ )
410
+ assert.strictEqual(allFailed.summary, "undefined,undefined")
411
+ assert.match(allFailed.system, /broken.*boom/)
412
+ assert.notInclude(allFailed.system, "searchTools")
413
+ }),
414
+ )
415
+
416
+ it.live("mcp and searchTools are reserved even without servers", () =>
417
+ Effect.gen(function* () {
418
+ const LoopTools = Toolkit.make(
419
+ Tool.make("searchTools", { parameters: Schema.String }),
420
+ )
421
+ const loopSide = yield* build(
422
+ Agent.makeWith({ loopTools: LoopTools }).pipe(
423
+ Effect.provide([
424
+ executorLayer("local"),
425
+ LoopTools.toLayer({ searchTools: () => Effect.void }),
426
+ ]),
427
+ ),
428
+ )
429
+ assert.notStrictEqual(loopSide, "built")
430
+ assert.include(loopSide, "searchTools")
431
+
432
+ const ExecutorTools = Toolkit.make(
433
+ Tool.make("mcp", { parameters: Schema.String }),
434
+ )
435
+ const executorSide = yield* build(
436
+ Agent.make.pipe(
437
+ Effect.provide(
438
+ executorLayer("local", { tools: ExecutorTools }).pipe(
439
+ Layer.provide(ExecutorTools.toLayer({ mcp: () => Effect.void })),
440
+ ),
441
+ ),
442
+ ),
443
+ )
444
+ assert.notStrictEqual(executorSide, "built")
445
+ assert.include(executorSide, "mcp")
446
+ }),
447
+ )
448
+
449
+ // --- naming ------------------------------------------------------------------
450
+
451
+ it.live("server and tool names are cleaned into identifiers", () =>
452
+ Effect.gen(function* () {
453
+ const { summary } = yield* runAgent({
454
+ script: `const s = mcp.brave_search
455
+ await taskComplete(JSON.stringify({
456
+ calls: await Promise.all([s.web_search({}), s.delete_({}), s._2fa({}), s.a_b({}), s.__proto__({})]),
457
+ types: await searchTools({ server: "brave_search" }),
458
+ none: await searchTools({ query: "zzz" }),
459
+ }))`,
460
+ })
461
+ const { calls, types, none } = JSON.parse(summary)
462
+ // Each call reaches the tool under its original name; of two tools that
463
+ // clean to the same identifier the first is kept.
464
+ assert.deepStrictEqual(calls, [
465
+ "web-search",
466
+ "delete",
467
+ "2fa",
468
+ "a-b",
469
+ "__proto__",
470
+ ])
471
+ assert.include(types, "declare namespace mcp.brave_search {")
472
+ assert.include(types, "function delete_(")
473
+ assert.strictEqual(count(types, /function a_b\(/g), 1)
474
+ assert.notInclude(types, "web-search")
475
+ // The skipped tool still counts.
476
+ assert.strictEqual(
477
+ none,
478
+ 'No MCP tools match "zzz". Servers: brave_search (6 tools).',
479
+ )
480
+
481
+ // The later server that cleans to a taken identifier fails, naming the
482
+ // server that holds it. Status keeps the original names.
483
+ const status = yield* currentStatus
484
+ assert.strictEqual(status["brave-search"]?._tag, "Connected")
485
+ assert.include(failure(status, "brave_search"), "brave-search")
486
+ }).pipe(
487
+ Effect.provide(
488
+ McpServers.layerTransports({
489
+ "brave-search": {
490
+ transport: fake({
491
+ tools: named(
492
+ "web-search",
493
+ "delete",
494
+ "2fa",
495
+ "a-b",
496
+ "a_b",
497
+ "__proto__",
498
+ ),
499
+ }).transport,
500
+ },
501
+ brave_search: {
502
+ transport: fake({ tools: named("other") }).transport,
503
+ },
504
+ }),
505
+ ),
506
+ ),
507
+ )
508
+
509
+ // --- discovery ---------------------------------------------------------------
510
+
511
+ it.live("searchTools finds tools by name, description and parameters", () =>
512
+ Effect.gen(function* () {
513
+ const { summary } = yield* runAgent({
514
+ script: `${attempt}
515
+ await taskComplete(JSON.stringify({
516
+ ranked: await searchTools({ query: "issue" }),
517
+ camel: await searchTools({ query: "pull" }),
518
+ parameter: await searchTools({ query: "owner" }),
519
+ capped: await searchTools({ query: "widget" }),
520
+ server: await searchTools({ server: "many" }),
521
+ neither: await attempt(searchTools({})),
522
+ unknown: await attempt(searchTools({ server: "nope" })),
523
+ none: await searchTools({ query: "zebra" }),
524
+ }))`,
525
+ })
526
+ const result = JSON.parse(summary)
527
+
528
+ // An exact name match ranks first, with its doc comments.
529
+ assert.include(result.ranked, "declare namespace mcp.github {")
530
+ assert.include(result.ranked, "/** Get one issue by number */")
531
+ assert.include(result.ranked, "/** Issue number */")
532
+ assert.isBelow(
533
+ result.ranked.indexOf("function issue("),
534
+ result.ranked.indexOf("function list_issues("),
535
+ )
536
+ assert.notInclude(result.ranked, "get_me")
537
+ assert.notInclude(result.ranked, "mcp.many")
538
+ assert.include(result.camel, "function createPullRequest(")
539
+ assert.include(result.parameter, "function list_issues(")
540
+ assert.notInclude(result.parameter, "function issue(")
541
+
542
+ // A query returns at most 10 tools; `server` alone lists all of them.
543
+ assert.strictEqual(count(result.capped, /function widget_/g), 10)
544
+ assert.strictEqual(count(result.server, /function widget_/g), 25)
545
+
546
+ for (const rejected of [result.neither, result.unknown]) {
547
+ assert.match(rejected, /^ERR /)
548
+ assert.include(rejected, "github")
549
+ assert.include(rejected, "many")
550
+ }
551
+ assert.strictEqual(
552
+ result.none,
553
+ 'No MCP tools match "zebra". Servers: github (4 tools), many (25 tools).',
554
+ )
555
+ }).pipe(
556
+ Effect.provide(
557
+ McpServers.layerTransports({
558
+ github: {
559
+ transport: fake({
560
+ tools: [
561
+ {
562
+ name: "issue",
563
+ description: "Get one issue by number",
564
+ inputSchema: {
565
+ type: "object",
566
+ properties: {
567
+ number: { type: "integer", description: "Issue number" },
568
+ },
569
+ required: ["number"],
570
+ },
571
+ },
572
+ {
573
+ name: "list_issues",
574
+ description: "List issues in a repository",
575
+ inputSchema: {
576
+ type: "object",
577
+ properties: { repository_owner: { type: "string" } },
578
+ },
579
+ },
580
+ {
581
+ name: "createPullRequest",
582
+ description: "Open a pull request",
583
+ },
584
+ { name: "get_me", description: "Get the authenticated user" },
585
+ ],
586
+ }).transport,
587
+ },
588
+ many: {
589
+ transport: fake({
590
+ tools: Array.from({ length: 25 }, (_, i) => ({
591
+ name: `widget_${i}`,
592
+ description: "Widget tool",
593
+ })),
594
+ }).transport,
595
+ },
596
+ }),
597
+ ),
598
+ ),
599
+ )
600
+
601
+ // --- calls -------------------------------------------------------------------
602
+
603
+ it.live("calls validate arguments and map results and errors", () =>
604
+ Effect.gen(function* () {
605
+ const { summary } = yield* runAgent({
606
+ script: `${attempt}
607
+ await taskComplete(JSON.stringify({
608
+ echo: await mcp.fake.echo({ text: "hi" }),
609
+ excess: await attempt(mcp.fake.echo({ text: "hi", extra: 1 })),
610
+ blocks: await mcp.fake.blocks({}),
611
+ empty: await mcp.fake.empty({}),
612
+ structured: await mcp.fake.structured({}),
613
+ badOutput: await attempt(mcp.fake.bad_output({})),
614
+ fails: await attempt(mcp.fake.fails({})),
615
+ failsSilently: await attempt(mcp.fake.fails_silently({})),
616
+ conditional: await mcp.fake.conditional({ anything: 1 }),
617
+ types: await searchTools({ server: "fake" }),
618
+ }))`,
619
+ })
620
+ const result = JSON.parse(summary)
621
+
622
+ assert.strictEqual(result.echo, '{"text":"hi"}')
623
+ assert.match(result.excess, /^ERR mcp\.fake\.echo: /)
624
+ assert.include(result.excess, "extra")
625
+ assert.match(
626
+ result.blocks,
627
+ /^first\n\[Image attached: fake\.blocks-\d+\.png\]\n\[Image omitted \(image\/bmp\): [^\]\n]+\]\n\[Audio omitted \(audio\/wav\)\]\n\[Resource file:\/\/\/notes\.txt\]\s+NOTES\n\[Binary resource omitted: file:\/\/\/data\.bin \(application\/octet-stream\)\]\n\[Resource link: design file:\/\/\/design\.md\]$/,
628
+ )
629
+ assert.strictEqual(result.empty, "")
630
+ // With an `outputSchema` the result is `structuredContent`.
631
+ assert.deepStrictEqual(result.structured, { login: "octocat" })
632
+ // `bad_output` is on the first page: every page's output validator is
633
+ // kept.
634
+ assert.match(result.badOutput, /^ERR mcp\.fake\.bad_output: /)
635
+ assert.strictEqual(result.fails, "ERR mcp.fake.fails: rate limited")
636
+ assert.strictEqual(
637
+ result.failsSilently,
638
+ "ERR mcp.fake.fails_silently: tool returned an error with no message",
639
+ )
640
+ // A schema that cannot be imported is not validated.
641
+ assert.strictEqual(result.conditional, '{"anything":1}')
642
+
643
+ assert.match(result.types, /function echo\([^]*?\): Promise<string>/)
644
+ assert.match(
645
+ result.types,
646
+ /function structured\([^]*?\): Promise<\{\s*readonly login: string;\s*\}>/,
647
+ )
648
+ assert.include(
649
+ result.types,
650
+ "function conditional(options: Record<string, unknown>)",
651
+ )
652
+ assert.include(result.types, '"then"')
653
+ }).pipe(
654
+ Effect.provide(
655
+ McpServers.layerTransports({
656
+ fake: {
657
+ transport: fake({
658
+ // One tool per page.
659
+ pageSize: 1,
660
+ tools: [
661
+ {
662
+ name: "bad_output",
663
+ outputSchema: {
664
+ type: "object",
665
+ properties: { login: { type: "string" } },
666
+ required: ["login"],
667
+ },
668
+ call: () => ({
669
+ content: [],
670
+ structuredContent: { login: 42 },
671
+ }),
672
+ },
673
+ {
674
+ name: "echo",
675
+ inputSchema: {
676
+ type: "object",
677
+ properties: { text: { type: "string" } },
678
+ required: ["text"],
679
+ additionalProperties: false,
680
+ },
681
+ call: (args) => text(JSON.stringify(args)),
682
+ },
683
+ {
684
+ name: "blocks",
685
+ call: () => ({
686
+ content: [
687
+ { type: "text", text: "first" },
688
+ {
689
+ type: "image",
690
+ data: Buffer.from(tinyPng).toString("base64"),
691
+ mimeType: "image/png",
692
+ },
693
+ { type: "image", data: "AAAA", mimeType: "image/bmp" },
694
+ { type: "audio", data: "AAAA", mimeType: "audio/wav" },
695
+ {
696
+ type: "resource",
697
+ resource: {
698
+ uri: "file:///notes.txt",
699
+ mimeType: "text/plain",
700
+ text: "NOTES",
701
+ },
702
+ },
703
+ {
704
+ type: "resource",
705
+ resource: {
706
+ uri: "file:///data.bin",
707
+ mimeType: "application/octet-stream",
708
+ blob: "AAAA",
709
+ },
710
+ },
711
+ {
712
+ type: "resource_link",
713
+ name: "design",
714
+ uri: "file:///design.md",
715
+ },
716
+ ],
717
+ }),
718
+ },
719
+ { name: "empty", call: () => ({ content: [] }) },
720
+ {
721
+ name: "structured",
722
+ outputSchema: {
723
+ type: "object",
724
+ properties: { login: { type: "string" } },
725
+ required: ["login"],
726
+ },
727
+ call: () => ({
728
+ content: [{ type: "text", text: "ignored" }],
729
+ structuredContent: { login: "octocat" },
730
+ }),
731
+ },
732
+ {
733
+ name: "fails",
734
+ call: () => ({ ...text("rate limited"), isError: true }),
735
+ },
736
+ {
737
+ name: "fails_silently",
738
+ call: () => ({ content: [], isError: true }),
739
+ },
740
+ {
741
+ name: "conditional",
742
+ inputSchema: {
743
+ type: "object",
744
+ if: { properties: { kind: { const: "a" } } },
745
+ // oxlint-disable-next-line unicorn/no-thenable
746
+ then: { required: ["a"] },
747
+ else: { required: ["b"] },
748
+ },
749
+ call: (args) => text(JSON.stringify(args)),
750
+ },
751
+ ],
752
+ }).transport,
753
+ },
754
+ }),
755
+ ),
756
+ ),
757
+ )
758
+
759
+ it.live("a dropped server is not reconnected", () => {
760
+ const server = fake({
761
+ tools: [
762
+ { name: "echo", call: () => text("echo") },
763
+ {
764
+ name: "crash",
765
+ call: (_, { close }) => {
766
+ void close()
767
+ return new Promise(() => {})
768
+ },
769
+ },
770
+ ],
771
+ })
772
+ return Effect.gen(function* () {
773
+ const { summary } = yield* runAgent({
774
+ script: `${attempt}
775
+ const crashed = await attempt(mcp.fake.crash({}))
776
+ await taskComplete(JSON.stringify({ crashed, after: await attempt(mcp.fake.echo({})) }))`,
777
+ })
778
+ const { crashed, after } = JSON.parse(summary)
779
+ assert.match(crashed, /^ERR mcp\.fake\.crash: /)
780
+ assert.match(
781
+ after,
782
+ /^ERR mcp\.fake\.echo: MCP server "fake" is not connected: /,
783
+ )
784
+ assert.strictEqual(server.connections, 1)
785
+ }).pipe(
786
+ Effect.provide(
787
+ McpServers.layerTransports({ fake: { transport: server.transport } }),
788
+ ),
789
+ )
790
+ })
791
+
792
+ it.live("a call that times out is cancelled on the server", () => {
793
+ const cancelled = Promise.withResolvers<void>()
794
+ return Effect.gen(function* () {
795
+ const { summary } = yield* runAgent({
796
+ script:
797
+ 'await taskComplete(await mcp.fake.wait({}).then(() => "resolved", (error) => error.message))',
798
+ })
799
+ assert.strictEqual(summary, "mcp.fake.wait: timed out after 50ms")
800
+ yield* Effect.promise(() => cancelled.promise).pipe(
801
+ Effect.timeout("2 seconds"),
802
+ )
803
+ }).pipe(
804
+ Effect.provide(
805
+ McpServers.layerTransports({
806
+ fake: {
807
+ callTimeout: Duration.millis(50),
808
+ transport: fake({
809
+ tools: [
810
+ {
811
+ name: "wait",
812
+ call: (_, { signal }) => {
813
+ signal.addEventListener("abort", () => cancelled.resolve())
814
+ return new Promise(() => {})
815
+ },
816
+ },
817
+ ],
818
+ }).transport,
819
+ },
820
+ }),
821
+ ),
822
+ )
823
+ })
824
+
825
+ // --- the Agent -----------------------------------------------------------------
826
+
827
+ for (const mode of modes) {
828
+ it.live(
829
+ `${mode} executor: sub-agents share the connection and images reach the model`,
830
+ () => {
831
+ const server = fake({
832
+ tools: [
833
+ { name: "ping", call: () => text("pong") },
834
+ {
835
+ name: "screenshot",
836
+ call: () => ({
837
+ content: [
838
+ {
839
+ type: "image",
840
+ data: Buffer.from(tinyPng).toString("base64"),
841
+ mimeType: "image/png",
842
+ },
843
+ ],
844
+ }),
845
+ },
846
+ ],
847
+ })
848
+ return Effect.gen(function* () {
849
+ const { summary, calls } = yield* runAgent({
850
+ mode,
851
+ script: (call) => {
852
+ if (call.role === "child") {
853
+ return "await taskComplete(await mcp.fake.ping({}))"
854
+ }
855
+ return call.index === 0
856
+ ? `const child = await delegate({ prompt: "TASK-CHILD" })
857
+ console.log(JSON.stringify(child))
858
+ console.log(await mcp.fake.screenshot({}))`
859
+ : 'await taskComplete("done")'
860
+ },
861
+ })
862
+ assert.strictEqual(summary, "done")
863
+ assert.strictEqual(server.connections, 1)
864
+ const root = calls.filter((call) => call.role === "root")
865
+ assert.strictEqual(root.length, 2)
866
+ const output = lastToolResult(root[1]!.prompt)
867
+ assert.include(output, "pong")
868
+ assert.match(output, /\[Image attached: fake\.screenshot-\d+\.png\]/)
869
+ assert.isTrue(hasPngAttachment(root[1]!.prompt))
870
+ }).pipe(
871
+ Effect.provide(
872
+ McpServers.layerTransports({
873
+ fake: { transport: server.transport },
874
+ }),
875
+ ),
876
+ )
877
+ },
878
+ )
879
+ }
880
+
881
+ // --- transports ----------------------------------------------------------------
882
+
883
+ it.live(
884
+ "stdio servers get the merged environment, report stderr and end with the scope",
885
+ () =>
886
+ Effect.gen(function* () {
887
+ const fs = yield* FileSystem.FileSystem
888
+ const path = yield* Path.Path
889
+ const out = path.join(yield* fs.makeTempDirectoryScoped(), "out.json")
890
+ yield* Effect.acquireRelease(
891
+ Effect.sync(() => {
892
+ process.env["FIXTURE_PARENT"] = "from-parent"
893
+ process.env["FIXTURE_TOKEN"] = "from-parent"
894
+ }),
895
+ () =>
896
+ Effect.sync(() => {
897
+ delete process.env["FIXTURE_PARENT"]
898
+ delete process.env["FIXTURE_TOKEN"]
899
+ }),
900
+ )
901
+
902
+ const status = yield* currentStatus.pipe(
903
+ Effect.provide(
904
+ McpServers.layer({
905
+ fixture: {
906
+ type: "stdio",
907
+ command: process.execPath,
908
+ args: [fixture(path)],
909
+ cwd: "src",
910
+ env: {
911
+ FIXTURE_OUT: Redacted.make(out),
912
+ FIXTURE_TOKEN: Redacted.make("from-config"),
913
+ },
914
+ },
915
+ exploding: {
916
+ type: "stdio",
917
+ command: process.execPath,
918
+ args: [fixture(path)],
919
+ env: { FIXTURE_FAIL: Redacted.make("fixture exploded") },
920
+ },
921
+ }),
922
+ ),
923
+ )
924
+ assert.strictEqual(status["fixture"]?._tag, "Connected")
925
+ assert.include(failure(status, "exploding"), "fixture exploded")
926
+
927
+ const started = JSON.parse(yield* fs.readFileString(out))
928
+ // A relative `cwd` resolves against the process cwd.
929
+ assert.strictEqual(started.cwd, path.resolve("src"))
930
+ assert.deepStrictEqual(started.env, {
931
+ FIXTURE_PARENT: "from-parent",
932
+ FIXTURE_TOKEN: "from-config",
933
+ })
934
+ // The layer's scope has closed.
935
+ yield* exited(started.pid)
936
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
937
+ )
938
+
939
+ it.live(
940
+ "a stdio server that fails to initialize has exited when the scope closes",
941
+ () =>
942
+ Effect.gen(function* () {
943
+ const fs = yield* FileSystem.FileSystem
944
+ const path = yield* Path.Path
945
+ const out = path.join(yield* fs.makeTempDirectoryScoped(), "out.json")
946
+ const status = yield* currentStatus.pipe(
947
+ Effect.provide(
948
+ McpServers.layer({
949
+ rejecting: {
950
+ type: "stdio",
951
+ command: process.execPath,
952
+ args: [fixture(path)],
953
+ env: {
954
+ FIXTURE_OUT: Redacted.make(out),
955
+ FIXTURE_REJECT_INIT: Redacted.make("1"),
956
+ },
957
+ },
958
+ }),
959
+ ),
960
+ )
961
+ assert.include(failure(status, "rejecting"), "initialize rejected")
962
+ // The server outlives its stdin, so it only ends once the shutdown
963
+ // the failed connect started is awaited.
964
+ const started = JSON.parse(yield* fs.readFileString(out))
965
+ assert.isFalse(isRunning(started.pid))
966
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
967
+ )
968
+
969
+ it.live("an http session the server ended is not connected", () =>
970
+ endedSession((url) => McpServers.layer({ remote: { type: "http", url } })),
971
+ )
972
+
973
+ it.live(
974
+ "an ended session on a caller-built SDK transport is not connected",
975
+ () =>
976
+ endedSession((url) =>
977
+ McpServers.layerTransports({
978
+ remote: {
979
+ transport: () =>
980
+ new StreamableHTTPClientTransport(new URL(url)) as Transport,
981
+ },
982
+ }),
983
+ ),
984
+ )
985
+
986
+ it.live("an http response resumes after its stream closes", () =>
987
+ Effect.gen(function* () {
988
+ const remote = yield* Effect.acquireRelease(
989
+ Effect.promise(() =>
990
+ listenHttp(
991
+ makeFakeServer({
992
+ tools: [
993
+ {
994
+ name: "slow",
995
+ call: async (_, { closeStream }) => {
996
+ closeStream()
997
+ await new Promise((resolve) => setTimeout(resolve, 100))
998
+ return text("resumed")
999
+ },
1000
+ },
1001
+ ],
1002
+ }),
1003
+ "/mcp",
1004
+ { resumable: true },
1005
+ ),
1006
+ ),
1007
+ (remote) => Effect.promise(remote.close),
1008
+ )
1009
+ const { summary, status } = yield* Effect.gen(function* () {
1010
+ const { summary } = yield* runAgent({
1011
+ script: "await taskComplete(await mcp.remote.slow({}))",
1012
+ })
1013
+ return { summary, status: yield* currentStatus }
1014
+ }).pipe(
1015
+ Effect.provide(
1016
+ McpServers.layer({ remote: { type: "http", url: remote.url } }),
1017
+ ),
1018
+ )
1019
+ assert.strictEqual(summary, "resumed")
1020
+ assert.strictEqual(status["remote"]?._tag, "Connected")
1021
+ }).pipe(Effect.scoped),
1022
+ )
1023
+
1024
+ it.live("http servers are sent the static headers", () =>
1025
+ Effect.gen(function* () {
1026
+ const remote = yield* Effect.acquireRelease(
1027
+ Effect.promise(() =>
1028
+ listenHttp(makeFakeServer({ tools: named("ping") })),
1029
+ ),
1030
+ (remote) => Effect.promise(remote.close),
1031
+ )
1032
+ const status = yield* currentStatus.pipe(
1033
+ Effect.provide(
1034
+ McpServers.layer({
1035
+ remote: {
1036
+ type: "http",
1037
+ url: remote.url,
1038
+ headers: { Authorization: Redacted.make("Bearer secret") },
1039
+ },
1040
+ }),
1041
+ ),
1042
+ )
1043
+ assert.strictEqual(status["remote"]?._tag, "Connected")
1044
+ assert.isNotEmpty(remote.authorization)
1045
+ for (const header of remote.authorization) {
1046
+ assert.strictEqual(header, "Bearer secret")
1047
+ }
1048
+ }).pipe(Effect.scoped),
1049
+ )
1050
+ })