Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 22x 22x 22x 22x 22x 22x 7x 7x 7x 7x 7x 7x 22x 22x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 11x 11x 11x | "use strict";
/**
* MCP server definition: exactly two tools, `search` and `execute`, with the
* same behaviour on every transport.
*
* @module server/tools
*/
import crypto from "node:crypto";
import { McpServer } from "@modelcontextprotocol/server";
import * as z from "zod";
import type { Principal } from "../types.js";
import { oagMcpVersion } from "../util/version.js";
import type { ClientEndpoint, OagMcpService } from "./service.js";
/** The only tools oag-mcp exposes. */
export const TOOL_NAMES = ["search", "execute"] as const;
/** Tool descriptions computed once per service (process). */
const DESCRIPTIONS = new WeakMap<
OagMcpService,
{ search: string; execute: string }
>();
/**
* Tool descriptions for a service, computed once.
*
* @private
*/
function _descriptions(service: OagMcpService): {
search: string;
execute: string;
} {
let d = DESCRIPTIONS.get(service);
if (!d) {
d = {
search: searchDescription(service),
execute: executeDescription(service),
};
DESCRIPTIONS.set(service, d);
}
return d;
}
/**
* Build the description of the execute tool.
*
* @param {Object} service - service
* @return {String} description
*/
export function executeDescription(service: OagMcpService): string {
const apis = service.apiClasses().join(", ");
return [
`Run JavaScript or TypeScript that calls the ${service.info.api.title} API through its generated SDK.`,
"Write the BODY of an async function: use `await`, combine several calls, loop, filter and aggregate, then `return` a JSON-serialisable result (keep it small).",
`A global \`sdk\` binding exposes the SDK API classes: ${apis}. Call methods as \`sdk.<ApiClass>.<method>(...)\` exactly as shown by the search tool; the base URL and credentials are configured by the server.`,
"No imports, network, filesystem, environment or subprocess access. `console.log` output is captured (bounded). TypeScript is type-checked against the SDK before running.",
"Example:\n```ts\nconst items = await sdk.PetsApi.listPets({ limit: 50 });\nreturn items.filter((p) => p.vaccinated).map((p) => p.name);\n```",
"Errors are structured: syntax_error, type_error (with diagnostics), api_error (HTTP status and body), permission_denied, timeout, output_limit, resource_limit.",
].join("\n\n");
}
/**
* Build the description of the search tool.
*
* @param {Object} service - service
* @return {String} description
*/
export function searchDescription(service: OagMcpService): string {
return [
`Discover methods of the ${service.info.api.title} SDK available to the execute tool.`,
'- `{ query }`: ranked full-text search (e.g. "list pets by species"); returns ids, signatures and summaries.',
"- `{ id }`: full details for one method: signature, input/return types, referenced type declarations, auth and an example.",
"- `{}` or `{ tag }`: browse API classes and their methods when you do not know the vocabulary yet.",
].join("\n");
}
/**
* Format a tool result with text and structured content.
*
* @private
*/
function _result(payload: Record<string, unknown>, isError = false) {
return {
content: [
{ type: "text" as const, text: JSON.stringify(payload, null, 2) },
],
structuredContent: payload,
isError,
};
}
/**
* Create an MCP server instance bound to one principal.
*
* @param {Object} service - service
* @param {Object} principal - authenticated principal
* @param {String} transport - transport name
* @param {String} [httpRequestId] - correlation id of the HTTP request
* @param {Object} [client] - address and port of the HTTP client
* @return {McpServer} server
*/
export function createMcpServer(
service: OagMcpService,
principal: Principal,
transport: "stdio" | "streamable-http",
httpRequestId?: string,
client: ClientEndpoint = {},
): McpServer {
const server = new McpServer(
{
name: "oag-mcp",
version: oagMcpVersion(),
title: `${service.info.api.title} (oag-mcp)`,
},
{
capabilities: { tools: {} },
instructions:
"Use `search` to find SDK methods (start with no arguments to browse), then `execute` TypeScript that calls them via the `sdk` binding. Return only the data you need.",
},
);
const requestId = () => httpRequestId ?? `req_${crypto.randomUUID()}`;
server.registerTool(
"search",
{
title: "Search SDK methods",
description: _descriptions(service).search,
inputSchema: z.object({
query: z
.string()
.max(500)
.optional()
.describe("Keywords describing what you want to do"),
id: z
.string()
.max(200)
.optional()
.describe(
"Exact method id from a previous result, e.g. 'PetsApi.listPets'",
),
tag: z
.string()
.max(200)
.optional()
.describe("Restrict to an API class or OpenAPI tag"),
limit: z
.number()
.int()
.min(1)
.max(20)
.optional()
.describe("Maximum results (default 5)"),
}),
// All four hints are set explicitly, even where the MCP spec says one
// does not apply, because some tool directories reject tools that
// leave any of them out.
annotations: {
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: false,
},
},
async (args, extra) => {
const out = service.search(args, {
principal,
requestId: requestId(),
transport,
...client,
mcpSessionId: extra.sessionId,
jsonrpcRequestId: extra.mcpReq.id,
});
return _result(out, Boolean(out.error));
},
);
server.registerTool(
"execute",
{
title: "Execute SDK code",
description: _descriptions(service).execute,
inputSchema: z.object({
code: z
.string()
.min(1)
.max(200000)
.describe("Body of an async function using the `sdk` binding"),
language: z
.enum(["typescript", "javascript"])
.optional()
.describe("Default: typescript (type-checked)"),
timeoutMs: z
.number()
.int()
.min(100)
.max(600000)
.optional()
.describe("Wall-clock limit for this execution"),
}),
annotations: {
readOnlyHint: false,
destructiveHint: true,
idempotentHint: false,
openWorldHint: true,
},
},
async (args, extra) => {
const out = await service.execute(args, {
principal,
requestId: requestId(),
transport,
...client,
mcpSessionId: extra.sessionId,
jsonrpcRequestId: extra.mcpReq.id,
});
return _result(out as unknown as Record<string, unknown>, !out.ok);
},
);
return server;
}
|