@silkweave/mcp 3.2.1 → 4.0.1
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.
- package/README.md +1 -1
- package/build/cliProxy.mjs +3 -3
- package/build/cliProxy.mjs.map +1 -1
- package/build/{registerTools-B_vjxOrs.mjs → filter-Baxr12pu.mjs} +52 -87
- package/build/filter-Baxr12pu.mjs.map +1 -0
- package/build/filter-BuYC4eO9.d.mts +60 -0
- package/build/filter-BuYC4eO9.d.mts.map +1 -0
- package/build/index.d.mts +4 -157
- package/build/index.d.mts.map +1 -1
- package/build/index.mjs +5 -299
- package/build/index.mjs.map +1 -1
- package/build/{result-I04HIJR5.d.mts → result-CQT2v6P1.d.mts} +3 -59
- package/build/result-CQT2v6P1.d.mts.map +1 -0
- package/build/{result-CXgeE8ca.mjs → result-uIqPNNxF.mjs} +20 -7
- package/build/result-uIqPNNxF.mjs.map +1 -0
- package/build/server.d.mts +163 -0
- package/build/server.d.mts.map +1 -0
- package/build/server.mjs +339 -0
- package/build/server.mjs.map +1 -0
- package/build/tools.d.mts +2 -1
- package/build/tools.mjs +2 -2
- package/package.json +8 -3
- package/build/registerTools-B_vjxOrs.mjs.map +0 -1
- package/build/result-CXgeE8ca.mjs.map +0 -1
- package/build/result-I04HIJR5.d.mts.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"registerTools-B_vjxOrs.mjs","names":[],"sources":["../src/handlers/auth.ts","../src/handlers/filter.ts","../src/handlers/registerTools.ts"],"sourcesContent":["import { AuthConfig, AuthInfo, validateToken } from '@silkweave/auth'\nimport { SilkweaveContext } from '@silkweave/core'\nimport { type RequestHandler } from 'express'\nimport { AsyncLocalStorage } from 'node:async_hooks'\n\n/**\n * Per-request bearer-token storage used by tool handlers to read the resolved\n * `AuthInfo` for the currently-handled MCP call.\n */\nexport const authStorage = new AsyncLocalStorage<AuthInfo>()\n\n/**\n * Express middleware that validates the `Authorization: Bearer …` header via\n * the supplied `AuthConfig`. On success the resolved `AuthInfo` is placed in\n * `authStorage` for the duration of the downstream handler - `mcpTransport`'s\n * tool callbacks pick it up to populate the silkweave context's `auth` key.\n *\n * The middleware should NOT be applied to OAuth-discovery / token routes -\n * compose it only on the routes that require an authenticated caller (the MCP\n * transport itself, sideload, etc.).\n */\nexport function authMiddleware(auth: AuthConfig, context: SilkweaveContext): RequestHandler {\n return async (req, res, next) => {\n const result = await validateToken(req.headers.authorization, auth, context.fork({ request: req }))\n if (result.error) {\n for (const [key, value] of Object.entries(result.error.headers)) { res.header(key, value) }\n res.status(result.error.statusCode).json(result.error.body)\n return\n }\n if (result.auth) {\n authStorage.run(result.auth, () => { next() })\n } else {\n next()\n }\n }\n}\n","import { Action, SilkweaveError } from '@silkweave/core'\n\n/**\n * Normalized request stand-in handed to `filterActions` - the same shape for\n * the Express `http()` transport and the Web-Standard `edge()` adapter.\n */\nexport interface FilterRequest {\n /** Inbound HTTP headers (lower-cased keys, as delivered by the host). */\n headers: Record<string, string | string[] | undefined>\n /** Full request URL (or path, as delivered by the host). */\n url: string\n /**\n * JSON-RPC method of the POSTed message (`'initialize'`, `'tools/list'`,\n * `'tools/call'`, `'ping'`, ...). Lets the callback skip expensive\n * permission lookups on `initialize`/`ping`, and doubles as an\n * observability tap (e.g. counting `tools/list`). Empty string when the body\n * is not a recognizable JSON-RPC message. JSON-RPC batches are rejected by the\n * transport before the filter runs, so this always reflects a single message.\n */\n method: string\n /** `params.name` of a `tools/call` message; unset for every other method. */\n toolName?: string\n}\n\n/**\n * Per-request tool filter for the stateless MCP transports. Runs before\n * `registerTools()` on every `POST /mcp`; only the returned actions exist for\n * that request (`tools/list` and `tools/call` alike - a client that cached a\n * wider list is still denied). May be async (e.g. a DB lookup of API-key\n * permissions).\n *\n * Error semantics: a thrown `SilkweaveError` propagates as its `statusCode`\n * (e.g. 401 invalid key, 403 insufficient permissions) with a JSON-RPC error\n * body; any other throw maps to HTTP 500. A thrown error NEVER degrades to an\n * empty tool list - return `[]` explicitly if \"no tools\" is the intended\n * answer.\n */\nexport type FilterActions = (actions: Action[], request: FilterRequest) => Action[] | Promise<Action[]>\n\n/**\n * Extract the JSON-RPC `method` (and `toolName` for `tools/call`) from a\n * parsed request body. Tolerates a legacy batch (first request wins) and\n * unrecognizable bodies (empty `method`).\n */\nexport function rpcInfo(body: unknown): { method: string; toolName?: string } {\n const message = (Array.isArray(body) ? body[0] : body) as { method?: unknown; params?: { name?: unknown } } | undefined\n const method = typeof message?.method === 'string' ? message.method : ''\n const toolName = method === 'tools/call' && typeof message?.params?.name === 'string' ? message.params.name : undefined\n return { method, ...(toolName !== undefined ? { toolName } : {}) }\n}\n\n/**\n * Map a `filterActions` throw to an HTTP status + JSON-RPC error body: a\n * `SilkweaveError` keeps its `statusCode` (so an invalid key surfaces as an\n * auth failure, not \"server has no tools\"), anything else is a 500. `id` is\n * echoed from the request body when available.\n */\nexport function filterErrorResponse(error: unknown, body: unknown): { status: number; body: object } {\n const message = (Array.isArray(body) ? body[0] : body) as { id?: unknown } | undefined\n const id = message?.id ?? null\n if (error instanceof SilkweaveError) {\n return {\n status: error.statusCode,\n body: { jsonrpc: '2.0', error: { code: -32_000, message: error.message }, id }\n }\n }\n console.error('filterActions error:', error)\n return {\n status: 500,\n body: { jsonrpc: '2.0', error: { code: -32_603, message: 'Internal server error' }, id }\n }\n}\n","import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js'\nimport type { ServerNotification, ServerRequest } from '@modelcontextprotocol/sdk/types.js'\nimport { Action, ActionRun, createLogger, emitToolCall, isStreamingAction, OnToolCall, runStreamingAction, SilkweaveContext, SilkweaveError, ToolCallEvent } from '@silkweave/core'\nimport { capitalCase, pascalCase } from 'change-case'\nimport { errorToolResult, handleToolError, jsonToolResult, smartToolResult, structuredToolResult } from '../util/result.js'\nimport { authStorage } from './auth.js'\n\ntype LogStream = NonNullable<Parameters<typeof createLogger>[0]>['stream']\ntype ToolExtra = RequestHandlerExtra<ServerRequest, ServerNotification>\n\nexport interface RegisterToolsOptions {\n /**\n * Where the per-call logger writes its human-readable stream. The `stdio`\n * adapter MUST pass `false` (stdout is the MCP protocol channel); the HTTP\n * transports default to `process.stderr`.\n */\n logStream?: LogStream\n /**\n * Telemetry hook invoked once per tool call (fire-and-forget; errors are\n * logged, never propagated). Fires after result formatting, so events carry\n * `resultBytes` (serialized raw-result size) and `sideloaded` (whether\n * `smartToolResult` offloaded to an embedded resource).\n */\n onToolCall?: OnToolCall\n}\n\n/**\n * Build the generic `request` context value (the same key REST/tRPC populate)\n * from the MCP SDK's `extra.requestInfo`, so transport-agnostic consumers - e.g.\n * `@silkweave/nestjs` `@UseGuards` guards reading\n * `switchToHttp().getRequest().headers` - work over MCP. There are no path\n * `params`/`query`/`body` on the raw MCP call, so those start as empty\n * stand-ins; `@silkweave/nestjs` later fills them from the validated tool input\n * per the reflected param sources (path -> `params`, `@Query` -> `query`,\n * `@Body` -> `body`) so guards reading any of them decide as they would over\n * REST. Returns `undefined` when no HTTP request info is available.\n */\nexport function requestFromExtra(requestInfo: { headers?: unknown; url?: { toString(): string } } | undefined) {\n if (!requestInfo) { return undefined }\n return { headers: requestInfo.headers ?? {}, url: requestInfo.url?.toString(), params: {}, query: {}, body: {} }\n}\n\n/** Per-call logger that bridges silkweave logs/progress onto MCP notifications. */\nfunction createToolLogger(extra: ToolExtra, stream: LogStream) {\n return createLogger({\n stream,\n onLog: (level, data) => {\n extra.sendNotification({ method: 'notifications/message', params: { level, data } })\n },\n onProgress: ({ progress, total, message }) => {\n if (!extra._meta?.progressToken) { return }\n extra.sendNotification({\n method: 'notifications/progress',\n params: { progress, total, message, progressToken: extra._meta.progressToken }\n })\n }\n })\n}\n\n/** Run the action, streaming chunks as progress notifications when a token is set. */\nasync function runAction(action: Action, input: object, context: SilkweaveContext, extra: ToolExtra): Promise<object | object[]> {\n const progressToken = extra._meta?.progressToken\n if (isStreamingAction(action)) {\n return runStreamingAction(action, input, context, progressToken\n ? async (chunk, index) => {\n await extra.sendNotification({\n method: 'notifications/progress',\n params: { progressToken, progress: index + 1, message: JSON.stringify(chunk) }\n })\n }\n : undefined)\n }\n return (action.run as ActionRun<object, object>)(input, context)\n}\n\n/**\n * Result path for a `disposition: 'structured'` action: parse the raw result\n * through the output schema and ship the PARSED data as `structuredContent`.\n * Parsing strips extra fields (so the client-side JSON-Schema validator, which\n * rejects `additionalProperties`, passes by construction) and a genuine\n * mismatch (missing required field, wrong type) degrades to an `isError` tool\n * result - which the SDK exempts from output validation - instead of an opaque\n * protocol error.\n */\nfunction structuredResult(action: Action, result: object | object[]) {\n const parsed = action.output!.safeParse(result)\n if (!parsed.success) {\n const fields = [...new Set(parsed.error.issues.map((issue) => issue.path.join('.') || '(root)'))].join(', ')\n return errorToolResult(new SilkweaveError(\n `Output validation failed for '${action.name}' at: ${fields}. The tool returned a shape that does not match its declared output schema - this is a server-side bug, not an input problem; retrying with different arguments will not help.`,\n 'output_validation_error'\n ))\n }\n // The SDK independently re-parses `structuredContent` against the same schema.\n // A non-idempotent output schema (a field-level `.transform()`) yields data\n // that fails that second parse, which the SDK raises as an opaque protocol\n // error. Detect it here and degrade to a clear isError result (SDK-exempt)\n // instead - structured contracts must be idempotent (no transforms).\n if (!action.output!.safeParse(parsed.data).success) {\n return errorToolResult(new SilkweaveError(\n `Output schema for '${action.name}' is not idempotent (a field-level .transform()?) and cannot back a 'structured' contract - use disposition 'json' or remove the transform.`,\n 'output_schema_not_structurable'\n ))\n }\n return structuredToolResult(parsed.data as object)\n}\n\n/** MCP-only telemetry fields, computed only when a hook is registered. */\nfunction resultMeta(result: object | object[], formatted: { content?: { type: string }[] }): Pick<ToolCallEvent, 'resultBytes' | 'sideloaded'> {\n return {\n // Actual UTF-8 byte count (String.length counts UTF-16 code units, which\n // understates multibyte payloads). TextEncoder keeps this edge-safe.\n resultBytes: new TextEncoder().encode(JSON.stringify(result)).length,\n sideloaded: (formatted.content ?? []).some((block) => block.type === 'resource')\n }\n}\n\n/** Error identity for telemetry: a SilkweaveError's `code`, else the error's name. */\nfunction errorMeta(error: unknown): Pick<ToolCallEvent, 'errorCode' | 'errorMessage'> {\n if (error instanceof SilkweaveError) { return { errorCode: error.code, errorMessage: error.message } }\n if (error instanceof Error) { return { errorCode: error.name, errorMessage: error.message } }\n return { errorCode: 'unknown' }\n}\n\n/** Format via the action's `toolResult` hook, else the resolved disposition. */\nfunction formatToolResult(action: Action, result: object | object[], context: SilkweaveContext, disposition: unknown) {\n if (action.toolResult) {\n const response = action.toolResult(result, context)\n if (response) { return response }\n }\n // A structured action's output schema is a contract fixed at tools/list\n // time - a client's `_meta.disposition` cannot demote it.\n if (action.disposition === 'structured') { return structuredResult(action, result) }\n return disposition === 'smart' ? smartToolResult(result) : jsonToolResult(result)\n}\n\n/**\n * Register every action as an MCP tool on `server`. Shared by all MCP transports\n * (`stdio`, `http`, `edge`). Each tool call forks `context` with a per-call\n * `logger`, the SDK `extra`, a synthesized `request` (see `requestFromExtra`),\n * and - when bearer auth ran for this request - the resolved `auth`. The result\n * is formatted by the action's `toolResult` hook if present, otherwise per the\n * resolved disposition (client `_meta.disposition` > `action.disposition` >\n * `json`); a `'structured'` action always ships schema-parsed\n * `structuredContent` (its contract cannot be demoted per-call).\n */\nexport function registerTools(\n server: McpServer,\n actions: Action[],\n context: SilkweaveContext,\n options: RegisterToolsOptions = {}\n) {\n const stream = options.logStream ?? process.stderr\n for (const action of actions) {\n server.registerTool(pascalCase(action.name), {\n title: capitalCase(action.name),\n description: action.description,\n inputSchema: action.input,\n // Derived base (query ⇒ read-only), explicit annotations merged over.\n annotations: { readOnlyHint: action.kind === 'query', ...action.annotations },\n // Only structured actions declare an outputSchema contract - the SDK\n // enforces it server-side and SDK clients enforce it independently, so\n // forwarding is strictly opt-in via disposition.\n ...(action.disposition === 'structured' && action.output ? { outputSchema: action.output } : {})\n }, async (input, extra) => {\n const logger = createToolLogger(extra, stream)\n const currentAuth = authStorage.getStore()\n const actionContext = context.fork({\n logger,\n extra,\n request: requestFromExtra(extra.requestInfo),\n ...(currentAuth ? { auth: currentAuth } : {})\n })\n // Client-sent `_meta.disposition` wins; otherwise fall back to the\n // action's configured default (`json` when neither is set).\n const disposition = extra._meta?.disposition ?? action.disposition\n const base = { action: action.name, tool: pascalCase(action.name), transport: 'mcp' as const, context: actionContext }\n const started = Date.now()\n try {\n const result = await runAction(action, input, actionContext, extra)\n const formatted = formatToolResult(action, result, actionContext, disposition)\n emitToolCall(options.onToolCall, {\n ...base,\n durationMs: Date.now() - started,\n ok: formatted.isError !== true,\n ...(options.onToolCall ? resultMeta(result, formatted) : {})\n })\n return formatted\n } catch (error) {\n emitToolCall(options.onToolCall, { ...base, durationMs: Date.now() - started, ok: false, ...errorMeta(error) })\n return handleToolError(error)\n }\n })\n }\n}\n"],"mappings":";;;;;;;;;;AASA,MAAa,cAAc,IAAI,mBAA6B;;;;;;;;;;;AAY5D,SAAgB,eAAe,MAAkB,SAA2C;AAC1F,QAAO,OAAO,KAAK,KAAK,SAAS;EAC/B,MAAM,SAAS,MAAM,cAAc,IAAI,QAAQ,eAAe,MAAM,QAAQ,KAAK,EAAE,SAAS,KAAK,CAAC,CAAC;AACnG,MAAI,OAAO,OAAO;AAChB,QAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,OAAO,MAAM,QAAQ,CAAI,KAAI,OAAO,KAAK,MAAM;AACzF,OAAI,OAAO,OAAO,MAAM,WAAW,CAAC,KAAK,OAAO,MAAM,KAAK;AAC3D;;AAEF,MAAI,OAAO,KACT,aAAY,IAAI,OAAO,YAAY;AAAE,SAAM;IAAG;MAE9C,OAAM;;;;;;;;;;ACYZ,SAAgB,QAAQ,MAAsD;CAC5E,MAAM,UAAW,MAAM,QAAQ,KAAK,GAAG,KAAK,KAAK;CACjD,MAAM,SAAS,OAAO,SAAS,WAAW,WAAW,QAAQ,SAAS;CACtE,MAAM,WAAW,WAAW,gBAAgB,OAAO,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AAG,EAAE;IAC5D,CAAC;AACF,UAAO;WACA,OAAO;AACd,gBAAa,QAAQ,YAAY;IAAE,GAAG;IAAM,YAAY,KAAK,KAAK,GAAG;IAAS,IAAI;IAAO,GAAG,UAAU,MAAM;IAAE,CAAC;AAC/G,UAAO,gBAAgB,MAAM;;GAE/B"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"result-CXgeE8ca.mjs","names":[],"sources":["../src/util/result.ts"],"sourcesContent":["import { EmbeddedResource, type CallToolResult } from '@modelcontextprotocol/sdk/types.js'\nimport { SilkweaveError } from '@silkweave/core'\nimport { randomUUID } from 'node:crypto'\n\nexport function smartToolResult(data: string | object | object[]): CallToolResult {\n const text = typeof data === 'string' ? data : JSON.stringify(data)\n const mimeType = typeof data === 'string' ? 'text/plain' : 'application/json'\n const ext = typeof data === 'string' ? 'txt' : 'json'\n if (text.length > 4096) {\n const uri = `mcp://toolResult/${randomUUID()}.${ext}`\n const buffer = Buffer.from(text)\n const blob = buffer.toString('base64')\n return {\n content: [\n { type: 'text', text: `Received resource ${uri} with ${buffer.byteLength} bytes` },\n { type: 'resource', resource: { uri, mimeType, blob } }\n ]\n }\n } else {\n return {\n content: [{ type: 'text' as const, text }]\n }\n }\n}\n\n/**\n * Result formatter for `disposition: 'structured'` actions: the (already\n * schema-parsed) data ships as `structuredContent` with a compact JSON text\n * mirror, per the spec's backwards-compat recommendation. Callers must pass\n * the OUTPUT-SCHEMA-PARSED data, not the raw result - parsing strips extra\n * fields, which is what keeps client-side JSON-Schema validation\n * (`additionalProperties: false`) passing by construction.\n */\nexport function structuredToolResult(data: object): CallToolResult {\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(data) }],\n structuredContent: data as Record<string, unknown>\n }\n}\n\nexport function jsonToolResult(data: object, isError = false): CallToolResult {\n const result: CallToolResult = { content: [{ type: 'text' as const, text: JSON.stringify(data) }] }\n if (isError) { result.isError = true }\n return result\n}\n\nexport function errorToolResult({ code, name, message }: SilkweaveError): CallToolResult {\n return {\n isError: true,\n content: [{\n type: 'text',\n text: JSON.stringify({ success: false, code, name, message })\n }]\n }\n}\n\nexport function handleToolError(error: unknown): CallToolResult {\n if (error instanceof SilkweaveError) {\n return jsonToolResult({ success: false, name: error.name, message: error.message, code: error.code }, true)\n } else if (error instanceof Error) {\n // Log the full error (incl. stack) to stderr only - never put the stack trace\n // on the wire, where it would leak server internals to the MCP client.\n console.error(error)\n return jsonToolResult({ success: false, name: error.name, message: error.message }, true)\n } else {\n // Likewise keep the raw thrown value server-side - only a generic message goes out.\n console.error('Unknown tool error:', error)\n return jsonToolResult({ success: false, name: 'Unknown error', message: 'An unknown error occurred' }, true)\n }\n}\n\nexport function parseResourceMessage({ resource }: EmbeddedResource) {\n const text = ('blob' in resource) ? Buffer.from(resource.blob, 'base64').toString('utf-8') : resource.text\n return text\n}\n"],"mappings":";;;AAIA,SAAgB,gBAAgB,MAAkD;CAChF,MAAM,OAAO,OAAO,SAAS,WAAW,OAAO,KAAK,UAAU,KAAK;CACnE,MAAM,WAAW,OAAO,SAAS,WAAW,eAAe;CAC3D,MAAM,MAAM,OAAO,SAAS,WAAW,QAAQ;AAC/C,KAAI,KAAK,SAAS,MAAM;EACtB,MAAM,MAAM,oBAAoB,YAAY,CAAC,GAAG;EAChD,MAAM,SAAS,OAAO,KAAK,KAAK;EAChC,MAAM,OAAO,OAAO,SAAS,SAAS;AACtC,SAAO,EACL,SAAS,CACP;GAAE,MAAM;GAAQ,MAAM,qBAAqB,IAAI,QAAQ,OAAO,WAAW;GAAS,EAClF;GAAE,MAAM;GAAY,UAAU;IAAE;IAAK;IAAU;IAAM;GAAE,CACxD,EACF;OAED,QAAO,EACL,SAAS,CAAC;EAAE,MAAM;EAAiB;EAAM,CAAC,EAC3C;;;;;;;;;;AAYL,SAAgB,qBAAqB,MAA8B;AACjE,QAAO;EACL,SAAS,CAAC;GAAE,MAAM;GAAiB,MAAM,KAAK,UAAU,KAAK;GAAE,CAAC;EAChE,mBAAm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