clanka 0.10.1 → 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 (103) hide show
  1. package/README.md +75 -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/AgentExecutor.test.js +24 -4
  14. package/dist/AgentExecutor.test.js.map +1 -1
  15. package/dist/AgentSkills.test.js +0 -1
  16. package/dist/AgentSkills.test.js.map +1 -1
  17. package/dist/AgentSubagents.test.js +16 -6
  18. package/dist/AgentSubagents.test.js.map +1 -1
  19. package/dist/AgentTools.d.ts +7 -0
  20. package/dist/AgentTools.d.ts.map +1 -1
  21. package/dist/AgentTools.js +7 -0
  22. package/dist/AgentTools.js.map +1 -1
  23. package/dist/McpConfig.d.ts +36 -0
  24. package/dist/McpConfig.d.ts.map +1 -0
  25. package/dist/McpConfig.js +182 -0
  26. package/dist/McpConfig.js.map +1 -0
  27. package/dist/McpConfig.test.d.ts +2 -0
  28. package/dist/McpConfig.test.d.ts.map +1 -0
  29. package/dist/McpConfig.test.js +163 -0
  30. package/dist/McpConfig.test.js.map +1 -0
  31. package/dist/McpServers.d.ts +176 -0
  32. package/dist/McpServers.d.ts.map +1 -0
  33. package/dist/McpServers.js +707 -0
  34. package/dist/McpServers.js.map +1 -0
  35. package/dist/McpServers.test.d.ts +2 -0
  36. package/dist/McpServers.test.d.ts.map +1 -0
  37. package/dist/McpServers.test.js +717 -0
  38. package/dist/McpServers.test.js.map +1 -0
  39. package/dist/TypeBuilder.d.ts +9 -0
  40. package/dist/TypeBuilder.d.ts.map +1 -1
  41. package/dist/TypeBuilder.js +24 -11
  42. package/dist/TypeBuilder.js.map +1 -1
  43. package/dist/TypeBuilder.test.js +33 -0
  44. package/dist/TypeBuilder.test.js.map +1 -1
  45. package/dist/bin/{Effect-2jPlJ8eu.mjs → Effect-DuThyCJ1.mjs} +155 -74
  46. package/dist/bin/Effect-DuThyCJ1.mjs.map +1 -0
  47. package/dist/bin/McpClient-CIiPyMDJ.mjs +36 -0
  48. package/dist/bin/McpClient-CIiPyMDJ.mjs.map +1 -0
  49. package/dist/bin/{OutputFormatter-BFAv48k9.mjs → OutputFormatter-BvIjvUmT.mjs} +3 -3
  50. package/dist/bin/{OutputFormatter-BFAv48k9.mjs.map → OutputFormatter-BvIjvUmT.mjs.map} +1 -1
  51. package/dist/bin/{Schema-D-7VuCiC.mjs → Schema-DcXUXpRg.mjs} +1069 -124
  52. package/dist/bin/Schema-DcXUXpRg.mjs.map +1 -0
  53. package/dist/bin/{SemanticSearch-Cb8aqvGv.mjs → SemanticSearch-CdGA4CIC.mjs} +27 -21
  54. package/dist/bin/SemanticSearch-CdGA4CIC.mjs.map +1 -0
  55. package/dist/bin/{Stream-DEu2tfCV.mjs → Stream-I9SRMlLj.mjs} +60 -45
  56. package/dist/bin/Stream-I9SRMlLj.mjs.map +1 -0
  57. package/dist/bin/cli.mjs +27217 -10325
  58. package/dist/bin/cli.mjs.map +1 -1
  59. package/dist/bin/{index.min-CI3qqohw.mjs → index.min-Bkz7vIWv.mjs} +7 -7
  60. package/dist/bin/index.min-Bkz7vIWv.mjs.map +1 -0
  61. package/dist/bin/rolldown-runtime-zY4HT0JA.mjs +30 -0
  62. package/dist/bin/{turndown.cjs-DK29wZw3.mjs → turndown.cjs-LntFxFyd.mjs} +2 -2
  63. package/dist/bin/{turndown.cjs-DK29wZw3.mjs.map → turndown.cjs-LntFxFyd.mjs.map} +1 -1
  64. package/dist/cli.js +46 -7
  65. package/dist/cli.js.map +1 -1
  66. package/dist/fixtures/McpFakeServer.d.ts +47 -0
  67. package/dist/fixtures/McpFakeServer.d.ts.map +1 -0
  68. package/dist/fixtures/McpFakeServer.js +112 -0
  69. package/dist/fixtures/McpFakeServer.js.map +1 -0
  70. package/dist/fixtures/McpStdioServer.d.ts +2 -0
  71. package/dist/fixtures/McpStdioServer.d.ts.map +1 -0
  72. package/dist/fixtures/McpStdioServer.js +53 -0
  73. package/dist/fixtures/McpStdioServer.js.map +1 -0
  74. package/dist/index.d.ts +4 -0
  75. package/dist/index.d.ts.map +1 -1
  76. package/dist/index.js +4 -0
  77. package/dist/index.js.map +1 -1
  78. package/package.json +14 -14
  79. package/src/Acp.test.ts +242 -0
  80. package/src/Acp.ts +141 -5
  81. package/src/Agent.ts +38 -10
  82. package/src/AgentExecutor.test.ts +31 -5
  83. package/src/AgentExecutor.ts +14 -1
  84. package/src/AgentSkills.test.ts +0 -1
  85. package/src/AgentSubagents.test.ts +20 -6
  86. package/src/AgentTools.ts +8 -0
  87. package/src/McpConfig.test.ts +238 -0
  88. package/src/McpConfig.ts +255 -0
  89. package/src/McpServers.test.ts +1050 -0
  90. package/src/McpServers.ts +1072 -0
  91. package/src/TypeBuilder.test.ts +70 -0
  92. package/src/TypeBuilder.ts +41 -14
  93. package/src/cli.ts +92 -8
  94. package/src/fixtures/McpFakeServer.ts +162 -0
  95. package/src/fixtures/McpStdioServer.ts +60 -0
  96. package/src/index.ts +5 -0
  97. package/dist/bin/Effect-2jPlJ8eu.mjs.map +0 -1
  98. package/dist/bin/McpClient-1W508adc.mjs +0 -14179
  99. package/dist/bin/McpClient-1W508adc.mjs.map +0 -1
  100. package/dist/bin/Schema-D-7VuCiC.mjs.map +0 -1
  101. package/dist/bin/SemanticSearch-Cb8aqvGv.mjs.map +0 -1
  102. package/dist/bin/Stream-DEu2tfCV.mjs.map +0 -1
  103. package/dist/bin/index.min-CI3qqohw.mjs.map +0 -1
@@ -1,10 +1,19 @@
1
1
  /** @effect-diagnostics schemaNumber:off */
2
+ import * as JsonSchema from "effect/JsonSchema"
2
3
  import * as Schema from "effect/Schema"
4
+ import * as SchemaRepresentation from "effect/SchemaRepresentation"
3
5
  import { describe, expect, it } from "vitest"
4
6
  import * as TypeBuilder from "./TypeBuilder.ts"
5
7
 
6
8
  const lines = (...parts: ReadonlyArray<string>): string => parts.join("\n")
7
9
 
10
+ // Imported as MCP tool schemas are.
11
+ const fromJsonSchema = (schema: JsonSchema.JsonSchema) =>
12
+ SchemaRepresentation.fromJsonSchemaDocument(
13
+ JsonSchema.fromSchemaDraft2020_12(schema),
14
+ { patterns: "ignore" },
15
+ )
16
+
8
17
  const primitiveCases = [
9
18
  ["string", Schema.String, "string"],
10
19
  ["number", Schema.Number, "number"],
@@ -506,4 +515,65 @@ describe("TypeBuilder", () => {
506
515
  ),
507
516
  ).toBe(lines("{", " readonly token: string", "}"))
508
517
  })
518
+
519
+ it("falls back to descriptions for property doc comments", () => {
520
+ // The importer attaches a check to integers and bounded strings.
521
+ expect(
522
+ TypeBuilder.render(
523
+ fromJsonSchema({
524
+ type: "object",
525
+ properties: {
526
+ owner: { type: "string", description: "Repository owner" },
527
+ count: { type: "integer", description: "How many" },
528
+ title: {
529
+ type: "string",
530
+ maxLength: 10,
531
+ description: "Short title",
532
+ },
533
+ },
534
+ required: ["owner"],
535
+ }),
536
+ ),
537
+ ).toBe(
538
+ lines(
539
+ "{",
540
+ " /** Repository owner */",
541
+ " readonly owner: string;",
542
+ " /** How many */",
543
+ " readonly count?: number;",
544
+ " /** Short title */",
545
+ " readonly title?: string;",
546
+ " [x: string]: unknown;",
547
+ "}",
548
+ ),
549
+ )
550
+ })
551
+
552
+ it("supports omitting unknown index signatures", () => {
553
+ expect(
554
+ TypeBuilder.render(
555
+ fromJsonSchema({
556
+ type: "object",
557
+ properties: {
558
+ login: { type: "string" },
559
+ labels: {
560
+ type: "object",
561
+ additionalProperties: { type: "string" },
562
+ },
563
+ },
564
+ required: ["login"],
565
+ }),
566
+ { omitUnknownIndexSignatures: true },
567
+ ),
568
+ ).toBe(
569
+ lines(
570
+ "{",
571
+ " readonly login: string;",
572
+ " readonly labels?: {",
573
+ " [x: string]: string;",
574
+ " };",
575
+ "}",
576
+ ),
577
+ )
578
+ })
509
579
  })
@@ -16,6 +16,11 @@ type Precedence = (typeof Precedence)[keyof typeof Precedence]
16
16
  export type PrinterOptions = {
17
17
  readonly newLine?: "\n" | "\r\n"
18
18
  readonly omitTrailingSemicolon?: boolean
19
+ /**
20
+ * Leave out `[x: string]: unknown` index signatures, which open objects
21
+ * imported from JSON Schema carry.
22
+ */
23
+ readonly omitUnknownIndexSignatures?: boolean
19
24
  }
20
25
 
21
26
  export type PrintableNode = {
@@ -47,6 +52,7 @@ const normalizeOptions = (
47
52
  ): Required<PrinterOptions> => ({
48
53
  newLine: options?.newLine ?? "\n",
49
54
  omitTrailingSemicolon: options?.omitTrailingSemicolon ?? false,
55
+ omitUnknownIndexSignatures: options?.omitUnknownIndexSignatures ?? false,
50
56
  })
51
57
 
52
58
  const indent = (level: number): string => " ".repeat(level)
@@ -79,13 +85,15 @@ const appendSuffix = (
79
85
  return lines.join(newLine)
80
86
  }
81
87
 
82
- const renderJsDoc = (
88
+ /**
89
+ * Renders a doc comment, each line prefixed with `indentation`.
90
+ */
91
+ export const renderJsDoc = (
83
92
  documentation: string,
84
- indentLevel: number,
85
- options: Required<PrinterOptions>,
93
+ indentation: string,
94
+ newLine: string = "\n",
86
95
  ): string => {
87
96
  const safeDocumentation = documentation.replaceAll("*/", "*\\/")
88
- const indentation = indent(indentLevel)
89
97
  const lines = safeDocumentation.split(/\r?\n/u)
90
98
 
91
99
  if (lines.length === 1) {
@@ -94,9 +102,9 @@ const renderJsDoc = (
94
102
 
95
103
  return [
96
104
  `${indentation}/**`,
97
- ...lines.map((line) => `${indentation} * ${line}`),
105
+ ...lines.map((line) => `${indentation} * ${line}`.trimEnd()),
98
106
  `${indentation} */`,
99
- ].join(options.newLine)
107
+ ].join(newLine)
100
108
  }
101
109
 
102
110
  const parenthesize = (text: string): string => `(${text})`
@@ -276,15 +284,20 @@ const propertySignatureTypeElement = (
276
284
  `${indent(indentLevel)}${readonlyModifier}${propertyName(propertySignature.name)}${optionalMarker}: `,
277
285
  context.options.newLine,
278
286
  )
279
- const documentation = resolveDocumentation(propertySignature.type)
287
+ // Schemas imported from JSON Schema carry `description`. It is read from
288
+ // the base node: `resolveAt` finds nothing on a node with checks.
289
+ const documentation =
290
+ resolveDocumentation(propertySignature.type) ??
291
+ propertySignature.type.annotations?.["description"]
280
292
 
281
- return documentation === undefined
293
+ return typeof documentation !== "string"
282
294
  ? propertyText
283
- : `${renderJsDoc(documentation, indentLevel, context.options)}${context.options.newLine}${propertyText}`
295
+ : `${renderJsDoc(documentation, indent(indentLevel), context.options.newLine)}${context.options.newLine}${propertyText}`
284
296
  }
285
297
 
286
298
  const indexSignatureTypeElement = (
287
299
  indexSignature: AST.IndexSignature,
300
+ valueType: RenderedType,
288
301
  context: RenderContext,
289
302
  indentLevel: number,
290
303
  ): string => {
@@ -293,7 +306,6 @@ const indexSignatureTypeElement = (
293
306
  context,
294
307
  indentLevel,
295
308
  )
296
- const valueType = toTypeNode(indexSignature.type, context, indentLevel)
297
309
 
298
310
  return prefixFirstLine(
299
311
  appendSuffix(
@@ -315,9 +327,24 @@ const objectsTypeNode = (
315
327
  ...ast.propertySignatures.map((propertySignature) =>
316
328
  propertySignatureTypeElement(propertySignature, context, indentLevel + 1),
317
329
  ),
318
- ...ast.indexSignatures.map((indexSignature) =>
319
- indexSignatureTypeElement(indexSignature, context, indentLevel + 1),
320
- ),
330
+ ...ast.indexSignatures.flatMap((indexSignature) => {
331
+ const valueType = toTypeNode(
332
+ indexSignature.type,
333
+ context,
334
+ indentLevel + 1,
335
+ )
336
+ return context.options.omitUnknownIndexSignatures &&
337
+ valueType.text === "unknown"
338
+ ? []
339
+ : [
340
+ indexSignatureTypeElement(
341
+ indexSignature,
342
+ valueType,
343
+ context,
344
+ indentLevel + 1,
345
+ ),
346
+ ]
347
+ }),
321
348
  ]
322
349
 
323
350
  return {
@@ -664,7 +691,7 @@ export const render = (
664
691
  text:
665
692
  documentation === undefined
666
693
  ? rendered.text
667
- : `${renderJsDoc(documentation, 0, printerOptions)}${printerOptions.newLine}${rendered.text}`,
694
+ : `${renderJsDoc(documentation, "", printerOptions.newLine)}${printerOptions.newLine}${rendered.text}`,
668
695
  },
669
696
  printerOptions,
670
697
  )
package/src/cli.ts CHANGED
@@ -14,6 +14,8 @@ import * as Copilot from "./Copilot.ts"
14
14
  import * as Xai from "./Xai.ts"
15
15
  import * as Agent from "./Agent.ts"
16
16
  import * as Compaction from "./Compaction.ts"
17
+ import * as McpConfig from "./McpConfig.ts"
18
+ import * as McpServers from "./McpServers.ts"
17
19
  import * as Stream from "effect/Stream"
18
20
  import * as Stdio from "effect/Stdio"
19
21
  import { pipe } from "effect/Function"
@@ -51,11 +53,20 @@ const withSubagentModel = <E, R>(
51
53
  >,
52
54
  ) => Layer.merge(model, Agent.layerSubagentModel(model))
53
55
 
54
- const modelLayer = (provider: Provider, model: string, effort: string) =>
56
+ const modelLayer = (
57
+ provider: Provider,
58
+ model: string,
59
+ effort: string,
60
+ openai: OpenAiClient.Options,
61
+ ) =>
55
62
  provider === "openai"
56
- ? withSubagentModel(
57
- Codex.modelWebSocket(model, { reasoning: { effort: effort as any } }),
58
- ).pipe(Layer.provide(Codex.layerClient))
63
+ ? openai.apiKey !== undefined
64
+ ? withSubagentModel(
65
+ Codex.model(model, { reasoning: { effort: effort as any } }),
66
+ ).pipe(Layer.provide(OpenAiClient.layer(openai)))
67
+ : withSubagentModel(
68
+ Codex.modelWebSocket(model, { reasoning: { effort: effort as any } }),
69
+ ).pipe(Layer.provide(Codex.layerClient))
59
70
  : provider === "xai"
60
71
  ? withSubagentModel(
61
72
  Xai.modelWebSocket(model, {
@@ -124,6 +135,20 @@ const provider = Flag.Literals("provider", providers).pipe(
124
135
 
125
136
  const model = Flag.String("model").pipe(Flag.withAlias("m"), Flag.optional)
126
137
 
138
+ const apiKey = Flag.Redacted("api-key").pipe(
139
+ Flag.withDescription("OpenAI API key (defaults to CLANKA_OPENAI_API_KEY)"),
140
+ Flag.withFallbackConfig(Config.Redacted("CLANKA_OPENAI_API_KEY")),
141
+ Flag.optional,
142
+ )
143
+
144
+ const apiUrl = Flag.String("api-url").pipe(
145
+ Flag.withDescription(
146
+ "OpenAI API base URL for API-key mode (defaults to CLANKA_OPENAI_API_URL or https://api.openai.com/v1)",
147
+ ),
148
+ Flag.withFallbackConfig(Config.String("CLANKA_OPENAI_API_URL")),
149
+ Flag.optional,
150
+ )
151
+
127
152
  const semantic = Flag.Directory("search").pipe(
128
153
  Flag.withDescription(
129
154
  "Directory for semantic search data (uses OPENAI_API_KEY env var)",
@@ -147,6 +172,35 @@ const compaction = Flag.Boolean("compaction").pipe(
147
172
  ),
148
173
  )
149
174
 
175
+ // Kill switch: `--no-mcp` or CLANKA_MCP=false.
176
+ const mcp = Flag.Boolean("mcp").pipe(
177
+ Flag.withDescription(
178
+ "Start the MCP servers from ~/.config/clanka/mcp.json, ./.mcp.json and --mcp-config. Disable with --no-mcp or CLANKA_MCP=false.",
179
+ ),
180
+ Flag.withFallbackConfig(
181
+ Config.Boolean("CLANKA_MCP").pipe(Config.withDefault(true)),
182
+ ),
183
+ )
184
+
185
+ const mcpConfig = Flag.String("mcp-config").pipe(
186
+ Flag.withDescription(
187
+ 'An MCP config file in the { "mcpServers": { ... } } format. Repeatable; a later file wins.',
188
+ ),
189
+ Flag.atLeast(0),
190
+ )
191
+
192
+ // One line after connecting, such as `MCP: github (26 tools), linear failed: ...`.
193
+ const mcpSummary = (
194
+ status: Readonly<Record<string, McpServers.ServerStatus>>,
195
+ ) =>
196
+ `MCP: ${Object.entries(status)
197
+ .map(([name, server]) =>
198
+ server._tag === "Connected"
199
+ ? `${name} (${server.tools.length} tools)`
200
+ : `${name} failed: ${server.error.split("\n")[0]}`,
201
+ )
202
+ .join(", ")}`
203
+
150
204
  const Kvs = Layer.unwrap(
151
205
  Effect.gen(function* () {
152
206
  const path = yield* Path.Path
@@ -208,11 +262,16 @@ const acpModel = Flag.String("model").pipe(
208
262
  Flag.map((modelId) => Option.getOrThrow(parseModelId(modelId))),
209
263
  )
210
264
 
211
- const acp = Command.make("acp", { model: acpModel, compaction }).pipe(
265
+ const acp = Command.make("acp", {
266
+ model: acpModel,
267
+ compaction,
268
+ apiKey,
269
+ apiUrl,
270
+ }).pipe(
212
271
  Command.withDescription(
213
272
  "Run as an Agent Client Protocol (ACP) server over stdio",
214
273
  ),
215
- Command.withHandler(({ model }) =>
274
+ Command.withHandler(({ model, apiKey, apiUrl }) =>
216
275
  Acp.runStdio({
217
276
  version,
218
277
  defaultModel: model.model,
@@ -223,7 +282,10 @@ const acp = Command.make("acp", { model: acpModel, compaction }).pipe(
223
282
  ),
224
283
  makeModel: (modelId, thoughtLevel) =>
225
284
  Option.map(parseAcpModelId(modelId), ({ provider, model }) =>
226
- modelLayer(provider, model, thoughtLevel),
285
+ modelLayer(provider, model, thoughtLevel, {
286
+ apiKey: Option.getOrUndefined(apiKey),
287
+ apiUrl: Option.getOrUndefined(apiUrl),
288
+ }),
227
289
  ),
228
290
  }),
229
291
  ),
@@ -243,6 +305,10 @@ Command.make("clanka", {
243
305
  semantic,
244
306
  prompt,
245
307
  compaction,
308
+ apiKey,
309
+ apiUrl,
310
+ mcp,
311
+ mcpConfig,
246
312
  }).pipe(
247
313
  Command.withHandler(
248
314
  Effect.fnUntraced(function* ({
@@ -250,8 +316,17 @@ Command.make("clanka", {
250
316
  model: modelRaw,
251
317
  semantic,
252
318
  prompt: nonInteractivePrompt,
319
+ apiKey,
320
+ apiUrl,
321
+ mcp,
322
+ mcpConfig,
253
323
  }) {
254
324
  const stdio = yield* Stdio.Stdio
325
+ const mcpServers = yield* McpConfig.load({
326
+ cwd: process.cwd(),
327
+ files: mcpConfig,
328
+ enabled: mcp,
329
+ })
255
330
  const OutputFormatter = yield* Effect.promise(
256
331
  () => import("./OutputFormatter.ts"),
257
332
  )
@@ -270,7 +345,10 @@ Command.make("clanka", {
270
345
  }),
271
346
  })
272
347
  const [model, reasoning] = selectedModel.split("/") as [string, string]
273
- const Model = modelLayer(provider, model, reasoning)
348
+ const Model = modelLayer(provider, model, reasoning, {
349
+ apiKey: Option.getOrUndefined(apiKey),
350
+ apiUrl: Option.getOrUndefined(apiUrl),
351
+ })
274
352
 
275
353
  return yield* Effect.gen(function* () {
276
354
  const agent = yield* Agent.Agent
@@ -284,6 +362,11 @@ Command.make("clanka", {
284
362
  )
285
363
  }
286
364
 
365
+ if (Object.keys(mcpServers).length > 0) {
366
+ const servers = yield* McpServers.McpServers
367
+ console.log(mcpSummary(yield* servers.status))
368
+ }
369
+
287
370
  while (true) {
288
371
  const prompt = yield* Prompt.String({
289
372
  message: ">",
@@ -309,6 +392,7 @@ Command.make("clanka", {
309
392
  onSome: Search,
310
393
  }),
311
394
  ),
395
+ Layer.provideMerge(McpServers.layer(mcpServers)),
312
396
  ),
313
397
  Model,
314
398
  ]),
@@ -0,0 +1,162 @@
1
+ import * as Http from "node:http"
2
+ import type { AddressInfo } from "node:net"
3
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js"
4
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"
5
+ import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"
6
+ import { InMemoryEventStore } from "@modelcontextprotocol/sdk/examples/shared/inMemoryEventStore.js"
7
+ import {
8
+ CallToolRequestSchema,
9
+ ListToolsRequestSchema,
10
+ type CallToolResult,
11
+ type Tool,
12
+ } from "@modelcontextprotocol/sdk/types.js"
13
+
14
+ /**
15
+ * A tool offered by the fake server. The schemas are raw JSON Schema, sent as
16
+ * they are in `tools/list`.
17
+ */
18
+ export interface FakeTool {
19
+ readonly name: string
20
+ readonly description?: string | undefined
21
+ readonly inputSchema?: Tool["inputSchema"] | undefined
22
+ readonly outputSchema?: Tool["outputSchema"] | undefined
23
+ readonly call?:
24
+ | ((
25
+ args: Record<string, unknown>,
26
+ context: {
27
+ readonly signal: AbortSignal
28
+ readonly close: () => Promise<void>
29
+ /** Ends a resumable HTTP response stream before the result. */
30
+ readonly closeStream: () => void
31
+ },
32
+ ) => CallToolResult | Promise<CallToolResult>)
33
+ | undefined
34
+ }
35
+
36
+ export const text = (value: string): CallToolResult => ({
37
+ content: [{ type: "text", text: value }],
38
+ })
39
+
40
+ /**
41
+ * A low-level SDK server, so `tools/list` can page and tools can carry any
42
+ * JSON Schema. `pageSize` defaults to every tool on one page.
43
+ */
44
+ export const makeFakeServer = (options: {
45
+ readonly tools: ReadonlyArray<FakeTool>
46
+ readonly pageSize?: number | undefined
47
+ readonly instructions?: string | undefined
48
+ }): Server => {
49
+ const server = new Server(
50
+ { name: "fake", version: "1.0.0" },
51
+ {
52
+ capabilities: { tools: {} },
53
+ ...(options.instructions !== undefined
54
+ ? { instructions: options.instructions }
55
+ : {}),
56
+ },
57
+ )
58
+ const pageSize = options.pageSize ?? options.tools.length
59
+ server.setRequestHandler(ListToolsRequestSchema, (request) => {
60
+ const start = Number(request.params?.cursor ?? 0)
61
+ const end = start + pageSize
62
+ return {
63
+ tools: options.tools.slice(start, end).map((tool) => {
64
+ const listed: Tool = {
65
+ name: tool.name,
66
+ inputSchema: tool.inputSchema ?? { type: "object" },
67
+ }
68
+ if (tool.description !== undefined) {
69
+ listed.description = tool.description
70
+ }
71
+ if (tool.outputSchema !== undefined) {
72
+ listed.outputSchema = tool.outputSchema
73
+ }
74
+ return listed
75
+ }),
76
+ ...(end < options.tools.length ? { nextCursor: String(end) } : {}),
77
+ }
78
+ })
79
+ server.setRequestHandler(CallToolRequestSchema, (request, extra) => {
80
+ const tool = options.tools.find((tool) => tool.name === request.params.name)
81
+ if (tool?.call === undefined) {
82
+ throw new Error(`unknown tool ${request.params.name}`)
83
+ }
84
+ return tool.call(request.params.arguments ?? {}, {
85
+ signal: extra.signal,
86
+ close: () => server.close(),
87
+ closeStream: () => extra.closeSSEStream?.(),
88
+ })
89
+ })
90
+ return server
91
+ }
92
+
93
+ /**
94
+ * Serves one fake server session over streamable HTTP on a loopback port.
95
+ *
96
+ * - `authorization` collects the header of every request.
97
+ * - `resumable` stores events, so a closed response stream can be resumed.
98
+ * - `endSession` answers every later request with 404, as a server does for
99
+ * a session it has ended. `afterEnd` lists those requests as
100
+ * `"<HTTP method> <JSON-RPC method>"`.
101
+ */
102
+ export const listenHttp = async (
103
+ server: Server,
104
+ path = "/mcp",
105
+ options: { readonly resumable?: boolean } = {},
106
+ ): Promise<{
107
+ readonly url: string
108
+ readonly authorization: ReadonlyArray<string | undefined>
109
+ readonly afterEnd: ReadonlyArray<string>
110
+ readonly endSession: () => void
111
+ readonly close: () => Promise<void>
112
+ }> => {
113
+ const transport = new StreamableHTTPServerTransport({
114
+ sessionIdGenerator: () => crypto.randomUUID(),
115
+ ...(options.resumable === true
116
+ ? { eventStore: new InMemoryEventStore(), retryInterval: 10 }
117
+ : {}),
118
+ })
119
+ // The SDK's optional callbacks predate `exactOptionalPropertyTypes`.
120
+ await server.connect(transport as Transport)
121
+ const authorization: Array<string | undefined> = []
122
+ const afterEnd: Array<string> = []
123
+ let ended = false
124
+ const http = Http.createServer((request, response) => {
125
+ authorization.push(request.headers.authorization)
126
+ if (!ended) {
127
+ void transport.handleRequest(request, response)
128
+ return
129
+ }
130
+ let body = ""
131
+ request.on("data", (chunk) => {
132
+ body += String(chunk)
133
+ })
134
+ request.on("end", () => {
135
+ const method = body === "" ? undefined : JSON.parse(body).method
136
+ afterEnd.push(`${request.method} ${method ?? ""}`.trim())
137
+ response.writeHead(404, { "content-type": "application/json" })
138
+ response.end(
139
+ JSON.stringify({
140
+ jsonrpc: "2.0",
141
+ id: null,
142
+ error: { code: -32001, message: "Session not found" },
143
+ }),
144
+ )
145
+ })
146
+ })
147
+ await new Promise<void>((resolve) => http.listen(0, "127.0.0.1", resolve))
148
+ const { port } = http.address() as AddressInfo
149
+ return {
150
+ url: `http://127.0.0.1:${port}${path}`,
151
+ authorization,
152
+ afterEnd,
153
+ endSession: () => {
154
+ ended = true
155
+ },
156
+ close: async () => {
157
+ http.closeAllConnections()
158
+ await new Promise((resolve) => http.close(resolve))
159
+ await server.close()
160
+ },
161
+ }
162
+ }
@@ -0,0 +1,60 @@
1
+ // A stdio MCP server run as a child process by the McpServers and Acp tests.
2
+ //
3
+ // - `FIXTURE_OUT`: a file the server writes `{ pid, cwd, env }` to at startup,
4
+ // where `env` holds `FIXTURE_PARENT` and `FIXTURE_TOKEN`.
5
+ // - `FIXTURE_FAIL`: write it to stderr and exit before connecting.
6
+ // - `FIXTURE_REJECT_INIT`: answer `initialize` with an error, and keep running
7
+ // after stdin closes, until signalled.
8
+ import * as Fs from "node:fs"
9
+ import * as Readline from "node:readline"
10
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
11
+ import { makeFakeServer, text } from "./McpFakeServer.ts"
12
+
13
+ const fail = process.env["FIXTURE_FAIL"]
14
+ if (fail !== undefined) {
15
+ process.stderr.write(`starting fixture\n${fail}\n`)
16
+ process.exit(1)
17
+ }
18
+
19
+ const out = process.env["FIXTURE_OUT"]
20
+ if (out !== undefined) {
21
+ Fs.writeFileSync(
22
+ out,
23
+ JSON.stringify({
24
+ pid: process.pid,
25
+ cwd: process.cwd(),
26
+ env: {
27
+ FIXTURE_PARENT: process.env["FIXTURE_PARENT"],
28
+ FIXTURE_TOKEN: process.env["FIXTURE_TOKEN"],
29
+ },
30
+ }),
31
+ )
32
+ }
33
+
34
+ process.stderr.write("fixture ready\n")
35
+
36
+ if (process.env["FIXTURE_REJECT_INIT"] !== undefined) {
37
+ setInterval(() => {}, 60_000)
38
+ Readline.createInterface({ input: process.stdin }).on("line", (line) => {
39
+ const message = JSON.parse(line)
40
+ if (message.method === "initialize") {
41
+ process.stdout.write(
42
+ `${JSON.stringify({
43
+ jsonrpc: "2.0",
44
+ id: message.id,
45
+ error: { code: -32603, message: "initialize rejected" },
46
+ })}\n`,
47
+ )
48
+ }
49
+ })
50
+ } else {
51
+ await makeFakeServer({
52
+ tools: [
53
+ {
54
+ name: "pid",
55
+ description: "Return the server's process id",
56
+ call: () => text(String(process.pid)),
57
+ },
58
+ ],
59
+ }).connect(new StdioServerTransport())
60
+ }
package/src/index.ts CHANGED
@@ -49,6 +49,11 @@ export * as GlobalWebSocket from "./GlobalWebSocket.ts"
49
49
  */
50
50
  export * as Image from "./Image.ts"
51
51
 
52
+ /**
53
+ * @since 1.0.0
54
+ */
55
+ export * as McpServers from "./McpServers.ts"
56
+
52
57
  /**
53
58
  * @since 1.0.0
54
59
  */