@bitbybit-dev/mcp 1.3.2-rc.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 (141) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +143 -0
  3. package/dist/context.d.ts +19 -0
  4. package/dist/context.d.ts.map +1 -0
  5. package/dist/context.js +28 -0
  6. package/dist/context.js.map +1 -0
  7. package/dist/descriptions.d.ts +10 -0
  8. package/dist/descriptions.d.ts.map +1 -0
  9. package/dist/descriptions.js +48 -0
  10. package/dist/descriptions.js.map +1 -0
  11. package/dist/guides-split.d.ts +9 -0
  12. package/dist/guides-split.d.ts.map +1 -0
  13. package/dist/guides-split.js +41 -0
  14. package/dist/guides-split.js.map +1 -0
  15. package/dist/guides.generated.d.ts +9 -0
  16. package/dist/guides.generated.d.ts.map +1 -0
  17. package/dist/guides.generated.js +93 -0
  18. package/dist/guides.generated.js.map +1 -0
  19. package/dist/index-loader.d.ts +11 -0
  20. package/dist/index-loader.d.ts.map +1 -0
  21. package/dist/index-loader.js +53 -0
  22. package/dist/index-loader.js.map +1 -0
  23. package/dist/index-reader.d.ts +27 -0
  24. package/dist/index-reader.d.ts.map +1 -0
  25. package/dist/index-reader.js +171 -0
  26. package/dist/index-reader.js.map +1 -0
  27. package/dist/index-shape.d.ts +3 -0
  28. package/dist/index-shape.d.ts.map +1 -0
  29. package/dist/index-shape.js +17 -0
  30. package/dist/index-shape.js.map +1 -0
  31. package/dist/index-types.d.ts +72 -0
  32. package/dist/index-types.d.ts.map +1 -0
  33. package/dist/index-types.js +2 -0
  34. package/dist/index-types.js.map +1 -0
  35. package/dist/index-url.d.ts +11 -0
  36. package/dist/index-url.d.ts.map +1 -0
  37. package/dist/index-url.js +30 -0
  38. package/dist/index-url.js.map +1 -0
  39. package/dist/index.d.ts +21 -0
  40. package/dist/index.d.ts.map +1 -0
  41. package/dist/index.js +14 -0
  42. package/dist/index.js.map +1 -0
  43. package/dist/installed-version.d.ts +18 -0
  44. package/dist/installed-version.d.ts.map +1 -0
  45. package/dist/installed-version.js +67 -0
  46. package/dist/installed-version.js.map +1 -0
  47. package/dist/json-schema.d.ts +2 -0
  48. package/dist/json-schema.d.ts.map +1 -0
  49. package/dist/json-schema.js +46 -0
  50. package/dist/json-schema.js.map +1 -0
  51. package/dist/registry.d.ts +56 -0
  52. package/dist/registry.d.ts.map +1 -0
  53. package/dist/registry.js +78 -0
  54. package/dist/registry.js.map +1 -0
  55. package/dist/render.d.ts +4 -0
  56. package/dist/render.d.ts.map +1 -0
  57. package/dist/render.js +76 -0
  58. package/dist/render.js.map +1 -0
  59. package/dist/results.d.ts +5 -0
  60. package/dist/results.d.ts.map +1 -0
  61. package/dist/results.js +18 -0
  62. package/dist/results.js.map +1 -0
  63. package/dist/server.d.ts +22 -0
  64. package/dist/server.d.ts.map +1 -0
  65. package/dist/server.js +69 -0
  66. package/dist/server.js.map +1 -0
  67. package/dist/stdio.d.ts +3 -0
  68. package/dist/stdio.d.ts.map +1 -0
  69. package/dist/stdio.js +64 -0
  70. package/dist/stdio.js.map +1 -0
  71. package/dist/tools/describe.d.ts +10 -0
  72. package/dist/tools/describe.d.ts.map +1 -0
  73. package/dist/tools/describe.js +39 -0
  74. package/dist/tools/describe.js.map +1 -0
  75. package/dist/tools/fetch.d.ts +9 -0
  76. package/dist/tools/fetch.d.ts.map +1 -0
  77. package/dist/tools/fetch.js +37 -0
  78. package/dist/tools/fetch.js.map +1 -0
  79. package/dist/tools/get-examples.d.ts +17 -0
  80. package/dist/tools/get-examples.d.ts.map +1 -0
  81. package/dist/tools/get-examples.js +60 -0
  82. package/dist/tools/get-examples.js.map +1 -0
  83. package/dist/tools/get-guide.d.ts +10 -0
  84. package/dist/tools/get-guide.d.ts.map +1 -0
  85. package/dist/tools/get-guide.js +64 -0
  86. package/dist/tools/get-guide.js.map +1 -0
  87. package/dist/tools/index.d.ts +4 -0
  88. package/dist/tools/index.d.ts.map +1 -0
  89. package/dist/tools/index.js +19 -0
  90. package/dist/tools/index.js.map +1 -0
  91. package/dist/tools/list-namespace.d.ts +10 -0
  92. package/dist/tools/list-namespace.d.ts.map +1 -0
  93. package/dist/tools/list-namespace.js +41 -0
  94. package/dist/tools/list-namespace.js.map +1 -0
  95. package/dist/tools/search-api.d.ts +16 -0
  96. package/dist/tools/search-api.d.ts.map +1 -0
  97. package/dist/tools/search-api.js +44 -0
  98. package/dist/tools/search-api.js.map +1 -0
  99. package/dist/tools/search.d.ts +9 -0
  100. package/dist/tools/search.d.ts.map +1 -0
  101. package/dist/tools/search.js +31 -0
  102. package/dist/tools/search.js.map +1 -0
  103. package/package.json +102 -0
  104. package/server.json +30 -0
  105. package/src/__fixtures__/index.sample.json +1916 -0
  106. package/src/__fixtures__/load.ts +29 -0
  107. package/src/context.ts +40 -0
  108. package/src/dependencies.test.ts +72 -0
  109. package/src/descriptions.ts +62 -0
  110. package/src/guides-split.ts +46 -0
  111. package/src/guides.generated.ts +95 -0
  112. package/src/guides.test.ts +57 -0
  113. package/src/index-loader.test.ts +160 -0
  114. package/src/index-loader.ts +61 -0
  115. package/src/index-reader.ts +179 -0
  116. package/src/index-shape.ts +17 -0
  117. package/src/index-types.ts +74 -0
  118. package/src/index-url.ts +29 -0
  119. package/src/index.ts +20 -0
  120. package/src/installed-version.test.ts +79 -0
  121. package/src/installed-version.ts +80 -0
  122. package/src/json-schema.test.ts +65 -0
  123. package/src/json-schema.ts +40 -0
  124. package/src/network.test.ts +37 -0
  125. package/src/registry.test.ts +177 -0
  126. package/src/registry.ts +139 -0
  127. package/src/render.ts +62 -0
  128. package/src/results.ts +21 -0
  129. package/src/server.test.ts +233 -0
  130. package/src/server.ts +117 -0
  131. package/src/stdio.test.ts +100 -0
  132. package/src/stdio.ts +67 -0
  133. package/src/tools/describe.ts +42 -0
  134. package/src/tools/docs-tools.test.ts +375 -0
  135. package/src/tools/fetch.ts +39 -0
  136. package/src/tools/get-examples.ts +59 -0
  137. package/src/tools/get-guide.ts +69 -0
  138. package/src/tools/index.ts +20 -0
  139. package/src/tools/list-namespace.ts +50 -0
  140. package/src/tools/search-api.ts +47 -0
  141. package/src/tools/search.ts +34 -0
@@ -0,0 +1,177 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { z } from "zod";
3
+ import { INTERNAL_ERROR_CODE, INTERNAL_ERROR_TEXT, Registry, TOOL_CEILING, guarded, inputJsonSchema, toHttp } from "./registry.js";
4
+ import type { ToolDefinition } from "./registry.js";
5
+
6
+ interface EchoContext {
7
+ prefix: string;
8
+ }
9
+
10
+ const echoInput = z.object({ text: z.string(), times: z.number().int().min(1).optional() });
11
+
12
+ const echo: ToolDefinition<typeof echoInput, EchoContext> = {
13
+ name: "echo",
14
+ description: "Repeats the text",
15
+ annotations: { title: "Echo", readOnlyHint: true, destructiveHint: false },
16
+ input: echoInput,
17
+ where: "server",
18
+ handler: (args, context) => ({ text: `${context.prefix}${args.text.repeat(args.times ?? 1)}`, structured: { times: args.times ?? 1 } }),
19
+ };
20
+
21
+ const declaredOnly: ToolDefinition<typeof echoInput, EchoContext> = {
22
+ name: "browser_only",
23
+ description: "Answered by the client application",
24
+ annotations: { title: "Browser only", readOnlyHint: true, destructiveHint: false },
25
+ input: echoInput,
26
+ where: "browser",
27
+ };
28
+
29
+ describe("Registry", () => {
30
+ it("lists tools in registration order and finds them by name", () => {
31
+ // Arrange
32
+ const registry = new Registry<EchoContext>().register(echo).register(declaredOnly);
33
+
34
+ // Act
35
+ const names = registry.list().map((definition) => definition.name);
36
+
37
+ // Assert
38
+ expect(names).toEqual(["echo", "browser_only"]);
39
+ expect(registry.get("echo")?.description).toBe("Repeats the text");
40
+ expect(registry.get("missing")).toBeUndefined();
41
+ expect(registry.size).toBe(2);
42
+ });
43
+
44
+ it("refuses a second tool of the same name", () => {
45
+ // Arrange
46
+ const registry = new Registry<EchoContext>().register(echo);
47
+
48
+ // Act & Assert
49
+ expect(() => registry.register(echo)).toThrow("already registered");
50
+ });
51
+
52
+ it("maps every handler into a new registry, leaving handler-less tools and the definitions as they are", async () => {
53
+ // Arrange
54
+ const registry = new Registry<EchoContext>().register(echo).register(declaredOnly);
55
+
56
+ // Act
57
+ const shouting = registry.map((handler) => async (args, context) => {
58
+ const result = await handler(args, context);
59
+ return { ...result, text: result.text.toUpperCase() };
60
+ });
61
+ const result = await shouting.get("echo")?.handler?.({ text: "hi", times: 2 }, { prefix: "> " });
62
+
63
+ // Assert
64
+ expect(result).toEqual({ text: "> HIHI", structured: { times: 2 } });
65
+ expect(shouting.list().map((definition) => definition.name)).toEqual(["echo", "browser_only"]);
66
+ expect(shouting.get("browser_only")?.handler).toBeUndefined();
67
+ expect(registry.get("echo")?.description).toBe("Repeats the text");
68
+ });
69
+
70
+ it("guards a throwing handler into a generic error result and reports the throw with the tool's name", async () => {
71
+ // Arrange
72
+ const reports: { error: unknown; tool: string }[] = [];
73
+ const broken: ToolDefinition<typeof echoInput, EchoContext> = { ...echo, name: "broken", handler: () => { throw new Error("Fetching https://internal.test failed"); } };
74
+ const safe = guarded(new Registry<EchoContext>().register(echo).register(broken), (error, tool) => reports.push({ error, tool }));
75
+
76
+ // Act
77
+ const failed = await safe.get("broken")?.handler?.({ text: "x" }, { prefix: "" });
78
+ const fine = await safe.get("echo")?.handler?.({ text: "x" }, { prefix: "" });
79
+
80
+ // Assert
81
+ expect(failed).toEqual({ text: INTERNAL_ERROR_TEXT, structured: { code: INTERNAL_ERROR_CODE }, isError: true });
82
+ expect(reports).toEqual([{ error: expect.objectContaining({ message: "Fetching https://internal.test failed" }), tool: "broken" }]);
83
+ expect(fine?.text).toBe("x");
84
+ });
85
+
86
+ it("keeps the ceiling at eight tools", () => {
87
+ // Assert
88
+ expect(TOOL_CEILING).toBe(8);
89
+ });
90
+ });
91
+
92
+ describe("toHttp", () => {
93
+ it("serves only tools with a handler, with their JSON schema", () => {
94
+ // Arrange
95
+ const registry = new Registry<EchoContext>().register(echo).register(declaredOnly);
96
+
97
+ // Act
98
+ const tools = toHttp(registry, { prefix: "" });
99
+
100
+ // Assert
101
+ expect(tools.map((tool) => tool.name)).toEqual(["echo"]);
102
+ expect(tools[0]?.inputSchema).toMatchObject({ type: "object", required: ["text"] });
103
+ expect(Object.keys(tools[0]?.inputSchema["properties"] ?? {})).toEqual(["text", "times"]);
104
+ });
105
+
106
+ it("calls the handler with parsed arguments and the context", async () => {
107
+ // Arrange
108
+ const registry = new Registry<EchoContext>().register(echo);
109
+ const [tool] = toHttp(registry, { prefix: "> " });
110
+
111
+ // Act
112
+ const result = await tool?.call({ text: "ab", times: 2 });
113
+
114
+ // Assert
115
+ expect(result).toEqual({ text: "> abab", structured: { times: 2 } });
116
+ });
117
+
118
+ it("answers invalid arguments with an error result instead of throwing", async () => {
119
+ // Arrange
120
+ const registry = new Registry<EchoContext>().register(echo);
121
+ const [tool] = toHttp(registry, { prefix: "" });
122
+
123
+ // Act
124
+ const result = await tool?.call({ times: 0 });
125
+
126
+ // Assert
127
+ expect(result?.isError).toBe(true);
128
+ expect(result?.text).toContain("Invalid arguments for echo");
129
+ });
130
+
131
+ it("applies a filter", () => {
132
+ // Arrange
133
+ const registry = new Registry<EchoContext>().register(echo);
134
+
135
+ // Act
136
+ const tools = toHttp(registry, { prefix: "" }, (definition) => definition.name !== "echo");
137
+
138
+ // Assert
139
+ expect(tools).toEqual([]);
140
+ });
141
+
142
+ it("renders the JSON schema of an input once and answers the same object afterwards", () => {
143
+ // Act
144
+ const first = inputJsonSchema(echoInput);
145
+ const second = inputJsonSchema(echoInput);
146
+
147
+ // Assert
148
+ expect(second).toBe(first);
149
+ expect(toHttp(new Registry<EchoContext>().register(echo), { prefix: "" })[0]?.inputSchema).toBe(first);
150
+ });
151
+
152
+ it("renders draft 2020-12 JSON schema for an input", () => {
153
+ // Act
154
+ const schema = inputJsonSchema(echoInput);
155
+
156
+ // Assert
157
+ expect(schema["$schema"]).toBe("https://json-schema.org/draft/2020-12/schema");
158
+ expect(schema["type"]).toBe("object");
159
+ });
160
+
161
+ it("inlines the definitions a registered id turns into references, and the pointers a reused schema turns into", () => {
162
+ // Arrange
163
+ const options = z.object({ formats: z.array(z.string()) }).meta({ id: "InlineTestOptions" });
164
+ const reused = z.object({ format: z.string() });
165
+ const body = z.object({ fileId: z.string(), outputs: options.optional(), first: reused, second: reused }).meta({ id: "InlineTestBody" });
166
+
167
+ // Act
168
+ const schema = inputJsonSchema(body);
169
+
170
+ // Assert
171
+ expect(schema["type"]).toBe("object");
172
+ expect(schema["$defs"]).toBeUndefined();
173
+ expect((schema["properties"] as Record<string, Record<string, unknown>>)["outputs"]?.["type"]).toBe("object");
174
+ expect((schema["properties"] as Record<string, Record<string, unknown>>)["second"]?.["type"]).toBe("object");
175
+ expect(JSON.stringify(schema)).not.toContain("$ref");
176
+ });
177
+ });
@@ -0,0 +1,139 @@
1
+ import { z } from "zod";
2
+ import { inlineJsonSchemaReferences } from "./json-schema.js";
3
+
4
+ export interface ToolAnnotations {
5
+ title: string;
6
+ readOnlyHint: boolean;
7
+ destructiveHint: boolean;
8
+ idempotentHint?: boolean;
9
+ openWorldHint?: boolean;
10
+ }
11
+
12
+ export interface ToolLink {
13
+ uri: string;
14
+ name: string;
15
+ mimeType?: string;
16
+ description?: string;
17
+ }
18
+
19
+ export interface ToolResult {
20
+ text: string;
21
+ structured?: Record<string, unknown>;
22
+ links?: ToolLink[];
23
+ isError?: boolean;
24
+ }
25
+
26
+ export type ToolWhere = "server" | "browser";
27
+
28
+ export type ToolInput = z.ZodObject<z.ZodRawShape>;
29
+
30
+ export type ToolHandler<TInput extends ToolInput, TContext> = (args: z.output<TInput>, context: TContext) => Promise<ToolResult> | ToolResult;
31
+
32
+ export interface ToolDefinition<TInput extends ToolInput, TContext> {
33
+ name: string;
34
+ description: string;
35
+ annotations: ToolAnnotations;
36
+ input: TInput;
37
+ where: ToolWhere;
38
+ scope?: string;
39
+ handler?: ToolHandler<TInput, TContext> | undefined;
40
+ }
41
+
42
+ export type AnyToolDefinition<TContext> = ToolDefinition<ToolInput, TContext>;
43
+
44
+ export const TOOL_CEILING = 8;
45
+
46
+ export class Registry<TContext> {
47
+ private readonly tools = new Map<string, AnyToolDefinition<TContext>>();
48
+
49
+ register<TInput extends ToolInput>(definition: ToolDefinition<TInput, TContext>): this {
50
+ if (this.tools.has(definition.name)) throw new Error(`Tool ${definition.name} is already registered`);
51
+ const { handler } = definition;
52
+ const erased: AnyToolDefinition<TContext> = handler
53
+ ? { ...definition, handler: (args, context) => handler(args as z.output<TInput>, context) }
54
+ : { ...definition, handler: undefined };
55
+ this.tools.set(definition.name, erased);
56
+ return this;
57
+ }
58
+
59
+ map(wrap: (handler: ToolHandler<ToolInput, TContext>, definition: AnyToolDefinition<TContext>) => ToolHandler<ToolInput, TContext>): Registry<TContext> {
60
+ const mapped = new Registry<TContext>();
61
+ for (const definition of this.list()) {
62
+ const { handler } = definition;
63
+ mapped.register(handler ? { ...definition, handler: wrap(handler, definition) } : definition);
64
+ }
65
+ return mapped;
66
+ }
67
+
68
+ list(): AnyToolDefinition<TContext>[] {
69
+ return [...this.tools.values()];
70
+ }
71
+
72
+ get(name: string): AnyToolDefinition<TContext> | undefined {
73
+ return this.tools.get(name);
74
+ }
75
+
76
+ get size(): number {
77
+ return this.tools.size;
78
+ }
79
+ }
80
+
81
+ const JSON_SCHEMAS = new WeakMap<ToolInput, Record<string, unknown>>();
82
+
83
+ export function inputJsonSchema(input: ToolInput): Record<string, unknown> {
84
+ const known = JSON_SCHEMAS.get(input);
85
+ if (known) return known;
86
+ const rendered = inlineJsonSchemaReferences(z.toJSONSchema(input, { target: "draft-2020-12", io: "input" }));
87
+ JSON_SCHEMAS.set(input, rendered);
88
+ return rendered;
89
+ }
90
+
91
+ export const INTERNAL_ERROR_CODE = "INTERNAL_ERROR";
92
+ export const INTERNAL_ERROR_TEXT = "An unexpected error occurred";
93
+
94
+ export type ErrorReporter<TContext> = (error: unknown, tool: string, context: TContext) => void;
95
+
96
+ export function guarded<TContext>(registry: Registry<TContext>, report: ErrorReporter<TContext>): Registry<TContext> {
97
+ return registry.map((handler, definition) => async (args, context): Promise<ToolResult> => {
98
+ try {
99
+ return await handler(args, context);
100
+ } catch (error) {
101
+ report(error, definition.name, context);
102
+ return { text: INTERNAL_ERROR_TEXT, structured: { code: INTERNAL_ERROR_CODE }, isError: true };
103
+ }
104
+ });
105
+ }
106
+
107
+ export interface HttpTool {
108
+ name: string;
109
+ description: string;
110
+ annotations: ToolAnnotations;
111
+ inputSchema: Record<string, unknown>;
112
+ call(args: unknown): Promise<ToolResult>;
113
+ }
114
+
115
+ export function toHttp<TContext>(
116
+ registry: Registry<TContext>,
117
+ context: TContext,
118
+ filter?: (definition: AnyToolDefinition<TContext>) => boolean,
119
+ ): HttpTool[] {
120
+ const tools: HttpTool[] = [];
121
+ for (const definition of registry.list()) {
122
+ const { handler } = definition;
123
+ if (!handler || (filter && !filter(definition))) continue;
124
+ tools.push({
125
+ name: definition.name,
126
+ description: definition.description,
127
+ annotations: definition.annotations,
128
+ inputSchema: inputJsonSchema(definition.input),
129
+ call: async (args: unknown): Promise<ToolResult> => {
130
+ const parsed = definition.input.safeParse(args);
131
+ if (!parsed.success) {
132
+ return { text: `Invalid arguments for ${definition.name}: ${z.prettifyError(parsed.error)}`, isError: true };
133
+ }
134
+ return handler(parsed.data, context);
135
+ },
136
+ });
137
+ }
138
+ return tools;
139
+ }
package/src/render.ts ADDED
@@ -0,0 +1,62 @@
1
+ import type { IndexExample, IndexField, IndexMember, IndexParam } from "./index-types.js";
2
+ import { TIER_MEANING } from "./descriptions.js";
3
+
4
+ function renderField(field: IndexField): string {
5
+ const parts = [`${field.name}${field.optional ? "?" : ""}: ${field.type}`];
6
+ if (field.default !== undefined) parts.push(`default ${JSON.stringify(field.default)}`);
7
+ if (field.min !== undefined || field.max !== undefined) parts.push(`range ${field.min ?? "..."} to ${field.max ?? "..."}`);
8
+ if (field.step !== undefined) parts.push(`step ${field.step}`);
9
+ if (field.options) parts.push(`one of ${field.options.map((option) => option.value).join(", ")}`);
10
+ const doc = field.doc ? ` - ${field.doc.replace(/\s+/g, " ")}` : "";
11
+ return `- ${parts.join("; ")}${doc}`;
12
+ }
13
+
14
+ function renderParam(param: IndexParam): string[] {
15
+ const head = `**${param.name}${param.optional ? "?" : ""}**: \`${param.type}\``;
16
+ if (!param.fields || param.fields.length === 0) return [head];
17
+ return [head, ...param.fields.map(renderField)];
18
+ }
19
+
20
+ function renderExample(example: IndexExample): string {
21
+ return ["```typescript", example.code, "```"].join("\n");
22
+ }
23
+
24
+ export function renderMember(member: IndexMember, version: string, examples: IndexExample[]): string {
25
+ const lines: string[] = [`# ${member.path}`, ""];
26
+ const facts = [`kind: ${member.kind}`, `tier: ${member.tier} (${TIER_MEANING[member.tier]})`, `version: ${version}`];
27
+ if (member.engines.length > 0) facts.push(`engines: ${member.engines.join(", ")}`);
28
+ if (member.onApi3d) facts.push("runs on CAD Cloud: yes");
29
+ if (member.endpoint) facts.push(`endpoint: ${member.httpMethod ?? "POST"} ${member.endpoint}`);
30
+ if (member.scope) facts.push(`API key scope: ${member.scope}`);
31
+ if (member.deprecated !== undefined) facts.push(member.deprecated ? `deprecated: ${member.deprecated}` : "deprecated");
32
+ if (member.drawable) facts.push("drawable: the result can be drawn directly");
33
+ lines.push(...facts.map((fact) => `- ${fact}`), "");
34
+ if (member.signature) lines.push("```typescript", member.signature, "```", "");
35
+ if (member.engineSignatures) {
36
+ lines.push("Signature by engine:", ...Object.entries(member.engineSignatures).map(([engine, signature]) => `- ${engine}: \`${signature ?? "none"}\``), "");
37
+ }
38
+ if (member.doc) lines.push(member.doc, "");
39
+ else if (member.summary) lines.push(member.summary, "");
40
+ if (member.params.length > 0) {
41
+ lines.push("## Parameters", "");
42
+ for (const param of member.params) lines.push(...renderParam(param));
43
+ lines.push("");
44
+ }
45
+ if (member.cloudParams) {
46
+ lines.push("## Parameters on CAD Cloud", "", "The signature above is the browser one; a cad_execute or pipeline step takes these inputs instead.", "");
47
+ if (member.cloudSummary) lines.push(member.cloudSummary, "");
48
+ for (const param of member.cloudParams) lines.push(...renderParam(param));
49
+ lines.push("");
50
+ }
51
+ if (member.returns) lines.push(`## Returns`, "", `\`${member.returns}\`${member.async ? " (async)" : ""}`, "");
52
+ if (examples.length > 0) {
53
+ lines.push("## Examples", "", ...examples.map(renderExample), "");
54
+ }
55
+ if (member.docUrl) lines.push(`Reference: ${member.docUrl}`);
56
+ return lines.join("\n").trimEnd() + "\n";
57
+ }
58
+
59
+ export function renderLine(member: IndexMember): string {
60
+ const tier = member.tier === "oss" ? "" : ` [${member.tier}]`;
61
+ return `- ${member.path} (${member.kind})${tier}${member.summary ? `: ${member.summary}` : ""}`;
62
+ }
package/src/results.ts ADDED
@@ -0,0 +1,21 @@
1
+ import type { ToolResult } from "./registry.js";
2
+ import { VersionNotLoadedError } from "./context.js";
3
+ import { IndexNotPublishedError } from "./index-url.js";
4
+
5
+ export function ok(text: string, structured?: Record<string, unknown>): ToolResult {
6
+ return structured ? { text, structured } : { text };
7
+ }
8
+
9
+ export function fail(text: string, structured?: Record<string, unknown>): ToolResult {
10
+ return structured ? { text, structured, isError: true } : { text, isError: true };
11
+ }
12
+
13
+ export function failFor(error: unknown): ToolResult {
14
+ if (error instanceof VersionNotLoadedError) {
15
+ return fail(error.message, { code: "VERSION_NOT_LOADED", requested: error.requested, loaded: error.loaded });
16
+ }
17
+ if (error instanceof IndexNotPublishedError) {
18
+ return fail(error.message, { code: "VERSION_NOT_PUBLISHED", version: error.version, ...(error.latest === undefined ? {} : { latest: error.latest }) });
19
+ }
20
+ throw error;
21
+ }
@@ -0,0 +1,233 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
3
+ import { createMcpServer, createRequestHandler } from "./server.js";
4
+ import { createDocsRegistry } from "./tools/index.js";
5
+ import { z } from "zod";
6
+ import { Registry, toHttp } from "./registry.js";
7
+ import { ok } from "./results.js";
8
+ import { DESCRIPTIONS, SERVER_INSTRUCTIONS, TOOL_NAMES } from "./descriptions.js";
9
+ import { FIXTURE_VERSION, fixtureContext } from "./__fixtures__/load.js";
10
+
11
+ async function connectedClient(): Promise<Client> {
12
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
13
+ const server = createMcpServer(createDocsRegistry(), fixtureContext(), { name: "bitbybit", version: FIXTURE_VERSION, instructions: SERVER_INSTRUCTIONS });
14
+ await server.connect(serverTransport);
15
+ const client = new Client({ name: "test-client", version: "0.0.0" });
16
+ await client.connect(clientTransport);
17
+ return client;
18
+ }
19
+
20
+ describe("the MCP binding", () => {
21
+ it("lists the seven tools with their titles, descriptions and read-only annotations", async () => {
22
+ // Arrange
23
+ const client = await connectedClient();
24
+
25
+ // Act
26
+ const { tools } = await client.listTools();
27
+
28
+ // Assert
29
+ expect(tools.map((tool) => tool.name)).toEqual([...TOOL_NAMES]);
30
+ for (const tool of tools) {
31
+ const expected = DESCRIPTIONS[tool.name as keyof typeof DESCRIPTIONS];
32
+ expect(tool.title).toBe(expected.title);
33
+ expect(tool.description).toBe(expected.description);
34
+ expect(tool.annotations).toMatchObject({ readOnlyHint: true, destructiveHint: false, openWorldHint: false });
35
+ }
36
+ });
37
+
38
+ it("advertises the same argument shapes the HTTP binding does", async () => {
39
+ // Arrange
40
+ const client = await connectedClient();
41
+ const http = toHttp(createDocsRegistry(), fixtureContext());
42
+
43
+ // Act
44
+ const { tools } = await client.listTools();
45
+
46
+ // Assert
47
+ for (const tool of tools) {
48
+ const twin = http.find((candidate) => candidate.name === tool.name);
49
+ const mcpProperties = Object.keys(tool.inputSchema.properties ?? {}).sort();
50
+ const httpProperties = Object.keys(twin?.inputSchema["properties"] ?? {}).sort();
51
+ expect(mcpProperties).toEqual(httpProperties);
52
+ expect(tool.inputSchema.required ?? []).toEqual(twin?.inputSchema["required"] ?? []);
53
+ }
54
+ });
55
+
56
+ it("advertises the inlined JSON schema of the HTTP binding, not a reference-laden one", async () => {
57
+ // Arrange
58
+ const client = await connectedClient();
59
+ const http = toHttp(createDocsRegistry(), fixtureContext());
60
+
61
+ // Act
62
+ const { tools } = await client.listTools();
63
+
64
+ // Assert
65
+ for (const tool of tools) {
66
+ const twin = http.find((candidate) => candidate.name === tool.name);
67
+ expect(tool.inputSchema).toEqual(twin?.inputSchema);
68
+ }
69
+ expect(JSON.stringify(tools)).not.toContain("\"$ref\":");
70
+ });
71
+
72
+ it("does not serve a tool the filter hides, so calling it is not found rather than refused", async () => {
73
+ // Arrange
74
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
75
+ const server = createMcpServer(createDocsRegistry(), fixtureContext(), { name: "bitbybit", version: FIXTURE_VERSION, filter: (definition) => definition.name !== "describe" });
76
+ await server.connect(serverTransport);
77
+ const client = new Client({ name: "test-client", version: "0.0.0" });
78
+ await client.connect(clientTransport);
79
+
80
+ // Act
81
+ const listed = (await client.listTools()).tools.map((tool) => tool.name);
82
+ const attempt = client.callTool({ name: "describe", arguments: { path: "occt" } });
83
+
84
+ // Assert
85
+ expect(listed).not.toContain("describe");
86
+ await expect(attempt).rejects.toThrow(/not found/);
87
+ });
88
+
89
+ it("answers describe with text and structured content carrying the version", async () => {
90
+ // Arrange
91
+ const client = await connectedClient();
92
+
93
+ // Act
94
+ const result = await client.callTool({ name: "describe", arguments: { path: "occt.shapes.solid.createBox" } });
95
+
96
+ // Assert
97
+ const content = result.content as { type: string; text: string }[];
98
+ expect(content[0]?.type).toBe("text");
99
+ expect(content[0]?.text).toContain("createBox(");
100
+ expect((result.structuredContent as { version: string }).version).toBe(FIXTURE_VERSION);
101
+ expect(result.isError).toBeFalsy();
102
+ });
103
+
104
+ it("hands a tool's links over as resource links after its text", async () => {
105
+ // Arrange
106
+ const registry = new Registry<Record<string, never>>().register({
107
+ name: "produce",
108
+ description: "Produces a file",
109
+ annotations: { title: "Produce", readOnlyHint: false, destructiveHint: false },
110
+ input: z.object({}),
111
+ where: "server",
112
+ handler: () => ({ text: "done", links: [{ uri: "https://files.test/result.glb", name: "result.glb", mimeType: "model/gltf-binary", description: "expires in 1 hour" }] }),
113
+ });
114
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
115
+ await createMcpServer(registry, {}, { name: "t", version: "0.0.0" }).connect(serverTransport);
116
+ const client = new Client({ name: "test-client", version: "0.0.0" });
117
+ await client.connect(clientTransport);
118
+
119
+ // Act
120
+ const result = await client.callTool({ name: "produce", arguments: {} });
121
+
122
+ // Assert
123
+ expect(result.content).toEqual([
124
+ { type: "text", text: "done" },
125
+ { type: "resource_link", uri: "https://files.test/result.glb", name: "result.glb", mimeType: "model/gltf-binary", description: "expires in 1 hour" },
126
+ ]);
127
+ });
128
+
129
+ it("carries the server instructions", async () => {
130
+ // Arrange
131
+ const client = await connectedClient();
132
+
133
+ // Act
134
+ const instructions = client.getInstructions();
135
+
136
+ // Assert
137
+ expect(instructions).toBe(SERVER_INSTRUCTIONS);
138
+ });
139
+ });
140
+
141
+ interface Caller {
142
+ who: string;
143
+ }
144
+
145
+ function callerRegistry(): Registry<Caller> {
146
+ return new Registry<Caller>()
147
+ .register({
148
+ name: "whoami",
149
+ description: "Names the caller",
150
+ annotations: { title: "Who am I", readOnlyHint: true, destructiveHint: false },
151
+ input: z.object({}),
152
+ where: "server",
153
+ handler: (_args, context) => ok(context.who),
154
+ })
155
+ .register({
156
+ name: "secret",
157
+ description: "Members only",
158
+ annotations: { title: "Secret", readOnlyHint: true, destructiveHint: false },
159
+ input: z.object({}),
160
+ where: "server",
161
+ handler: () => ok("the secret"),
162
+ });
163
+ }
164
+
165
+ function rpc(method: string, params: Record<string, unknown> = {}): Request {
166
+ return new Request("https://mcp.test/mcp", {
167
+ method: "POST",
168
+ headers: { "content-type": "application/json", accept: "application/json, text/event-stream" },
169
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
170
+ });
171
+ }
172
+
173
+ async function reply(response: Response): Promise<{ result?: Record<string, unknown>; error?: { message: string } }> {
174
+ const text = await response.text();
175
+ const data = text.split("\n").find((line) => line.startsWith("data: "));
176
+ return JSON.parse(data === undefined ? text : data.slice("data: ".length)) as { result?: Record<string, unknown>; error?: { message: string } };
177
+ }
178
+
179
+ describe("the request handler", () => {
180
+ it("serves every request through one handler with the context that request carries", async () => {
181
+ // Arrange
182
+ const handler = createRequestHandler(callerRegistry(), {
183
+ name: "t",
184
+ version: "0.0.0",
185
+ filterFor: (context) => (definition) => context.who !== "guest" || definition.name !== "secret",
186
+ });
187
+
188
+ // Act
189
+ const member = await reply(await handler.fetch(rpc("tools/list"), { who: "member" }));
190
+ const guest = await reply(await handler.fetch(rpc("tools/list"), { who: "guest" }));
191
+ const named = await reply(await handler.fetch(rpc("tools/call", { name: "whoami", arguments: {} }), { who: "alice" }));
192
+ const hidden = await reply(await handler.fetch(rpc("tools/call", { name: "secret", arguments: {} }), { who: "guest" }));
193
+
194
+ // Assert
195
+ const names = (listed: Record<string, unknown> | undefined): string[] => ((listed?.["tools"] ?? []) as { name: string }[]).map((tool) => tool.name);
196
+ expect(names(member.result)).toEqual(["whoami", "secret"]);
197
+ expect(names(guest.result)).toEqual(["whoami"]);
198
+ expect((named.result?.["content"] as { text: string }[])[0]?.text).toBe("alice");
199
+ expect(hidden.error?.message).toContain("secret");
200
+ });
201
+
202
+ it("reports a failure of its own to onError and still answers an internal error", async () => {
203
+ // Arrange
204
+ const reported: Error[] = [];
205
+ const handler = createRequestHandler(callerRegistry(), {
206
+ name: "t",
207
+ version: "0.0.0",
208
+ filterFor: () => { throw new Error("the filter broke"); },
209
+ onError: (error) => reported.push(error),
210
+ });
211
+
212
+ // Act
213
+ const response = await handler.fetch(rpc("tools/list"), { who: "member" });
214
+ const answer = await reply(response);
215
+
216
+ // Assert
217
+ expect(response.status).toBe(500);
218
+ expect(answer.error?.message).toContain("Internal server error");
219
+ expect(reported.map((error) => error.message)).toEqual(["the filter broke"]);
220
+ });
221
+
222
+ it("carries the server name, version and instructions", async () => {
223
+ // Arrange
224
+ const handler = createRequestHandler(callerRegistry(), { name: "bitbybit", version: FIXTURE_VERSION, instructions: SERVER_INSTRUCTIONS });
225
+
226
+ // Act
227
+ const initialized = await reply(await handler.fetch(rpc("initialize", { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "test-client", version: "0.0.0" } }), { who: "member" }));
228
+
229
+ // Assert
230
+ expect(initialized.result?.["serverInfo"]).toMatchObject({ name: "bitbybit", version: FIXTURE_VERSION });
231
+ expect(initialized.result?.["instructions"]).toBe(SERVER_INSTRUCTIONS);
232
+ });
233
+ });