@talonic/mcp 0.1.25 → 0.1.26
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/CHANGELOG.md +2 -0
- package/dist/content.js +543 -19
- package/dist/content.js.map +1 -1
- package/dist/http-server.js +1 -1
- package/dist/http-server.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/server.js +1 -1
- package/dist/server.js.map +1 -1
- package/package.json +1 -1
package/dist/http-server.js
CHANGED
package/dist/http-server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/resources/schemas-resource.ts","../src/resources/webhooks-resource.ts","../src/tools/_shared.ts","../src/tools/extract.ts","../src/tools/filter.ts","../src/tools/get-balance.ts","../src/tools/get-document.ts","../src/tools/list-schemas.ts","../src/tools/save-schema.ts","../src/tools/search.ts","../src/tools/to-markdown.ts","../package.json","../src/version.ts","../src/server-factory.ts","../src/http-server.ts"],"names":["DESCRIPTION","z","inputSchema","outputSchema","TalonicError","createHttpServer"],"mappings":";;;;;;;;;;;AAcO,SAAS,uBAAA,CAAwB,QAAmB,UAAA,EAAiC;AAC1F,EAAA,MAAA,CAAO,gBAAA;AAAA,IACL,iBAAA;AAAA,IACA,mBAAA;AAAA,IACA;AAAA,MACE,KAAA,EAAO,iBAAA;AAAA,MACP,WAAA,EACE,6FAAA;AAAA,MACF,QAAA,EAAU;AAAA,KACZ;AAAA,IACA,OAAO,GAAA,KAAQ;AACb,MAAA,MAAM,MAAA,GAAS,MAAM,UAAA,EAAW,CAAE,QAAQ,IAAA,EAAK;AAC/C,MAAA,OAAO;AAAA,QACL,QAAA,EAAU;AAAA,UACR;AAAA,YACE,GAAA,EAAK,IAAI,QAAA,EAAS;AAAA,YAClB,QAAA,EAAU,kBAAA;AAAA,YACV,IAAA,EAAM,IAAA,CAAK,SAAA,CAAU,MAAA,EAAQ,MAAM,CAAC;AAAA;AACtC;AACF,OACF;AAA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AI,OAAO,CAAA,6BAAA,EAAgC,IAAI,CAAA,IAAA,CAAM,CAAA;AAC/E,EAAA,OAAA,CAAQ,GAAA,CAAI,CAAA,6BAAA,EAAgC,IAAI,CAAA,OAAA,CAAS,CAAA;AAC3D,CAAC,CAAA","file":"http-server.js","sourcesContent":["import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\"\nimport type { Talonic } from \"@talonic/node\"\n\n/**\n * Register the `talonic://schemas` resource. The agent can read this\n * URI to retrieve the user's saved schemas without burning a tool call.\n *\n * The MCP SDK exposes resources as a separate primitive from tools.\n * Clients (Claude Desktop, Cursor, etc.) display them in their UI\n * alongside the conversation, so users can browse what their agent has\n * access to.\n *\n * @internal\n */\nexport function registerSchemasResource(server: McpServer, getTalonic: () => Talonic): void {\n server.registerResource(\n \"talonic-schemas\",\n \"talonic://schemas\",\n {\n title: \"Talonic Schemas\",\n description:\n \"All schemas saved in the user's Talonic workspace, with their full JSON Schema definitions.\",\n mimeType: \"application/json\",\n },\n async (uri) => {\n const result = await getTalonic().schemas.list()\n return {\n contents: [\n {\n uri: uri.toString(),\n mimeType: \"application/json\",\n text: JSON.stringify(result, null, 2),\n },\n ],\n }\n },\n )\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\"\n\n/**\n * Webhook reference info fetched from the Talonic API.\n * These endpoints don't require a request body — just auth.\n */\nconst WEBHOOK_INFO_ENDPOINTS = [\n { path: \"/v1/webhooks/events\", key: \"events\", description: \"Available webhook event types\" },\n {\n path: \"/v1/webhooks/delivery\",\n key: \"delivery\",\n description: \"Delivery behavior and retry policy\",\n },\n {\n path: \"/v1/webhooks/signatures\",\n key: \"signatures\",\n description: \"Signature verification algorithms\",\n },\n {\n path: \"/v1/webhooks/retries\",\n key: \"retries\",\n description: \"Retry schedule and backoff policy\",\n },\n] as const\n\n/**\n * Register the `talonic://webhooks/reference` resource.\n *\n * Aggregates the four webhook info routes into a single resource so\n * agents can look up event types, delivery semantics, signature\n * algorithms, and retry policies without leaving the MCP context.\n *\n * @internal\n */\nexport function registerWebhooksResource(\n server: McpServer,\n getToken: () => string,\n baseUrl?: string,\n): void {\n const base = baseUrl ?? \"https://api.talonic.com\"\n\n server.registerResource(\n \"talonic-webhooks-reference\",\n \"talonic://webhooks/reference\",\n {\n title: \"Talonic Webhooks Reference\",\n description:\n \"Webhook event types, delivery behavior, signature verification algorithms, and retry policies.\",\n mimeType: \"application/json\",\n },\n async (uri) => {\n const results: Record<string, unknown> = {}\n // Resolve the token once per resource read so a token rotated\n // mid-session (OAuth 2.1 access tokens) is picked up on the next read.\n const token = getToken()\n\n await Promise.all(\n WEBHOOK_INFO_ENDPOINTS.map(async ({ path, key }) => {\n try {\n const res = await fetch(`${base}${path}`, {\n headers: {\n Authorization: `Bearer ${token}`,\n Accept: \"application/json\",\n },\n })\n if (res.ok) {\n results[key] = await res.json()\n } else {\n results[key] = {\n error: `HTTP ${res.status}`,\n message: await res.text().catch(() => \"\"),\n }\n }\n } catch (err) {\n results[key] = {\n error: \"fetch_failed\",\n message: err instanceof Error ? err.message : String(err),\n }\n }\n }),\n )\n\n return {\n contents: [\n {\n uri: uri.toString(),\n mimeType: \"application/json\",\n text: JSON.stringify(results, null, 2),\n },\n ],\n }\n },\n )\n}\n","import { TalonicError } from \"@talonic/node\"\n\n/**\n * Successful tool result envelope. The `content` array follows the MCP\n * `CallToolResult` shape. We always emit one text item with the JSON\n * payload; agents parse it back themselves.\n *\n * The `[key: string]: unknown` index signature exists to satisfy the\n * MCP SDK's structural type, which permits arbitrary additional keys.\n *\n * @internal\n */\nexport interface ToolSuccessResult {\n content: Array<{ type: \"text\"; text: string }>\n [key: string]: unknown\n}\n\n/**\n * Failure tool result envelope. Sets `isError: true` per the MCP spec\n * so clients render this as an error rather than a normal response.\n *\n * @internal\n */\nexport interface ToolErrorResult {\n content: Array<{ type: \"text\"; text: string }>\n isError: true\n [key: string]: unknown\n}\n\nexport type ToolResult = ToolSuccessResult | ToolErrorResult\n\n/**\n * Wrap a value as a tool result. Returns both the legacy text envelope\n * (`content[0].text`) for clients that parse strings, and the\n * `structuredContent` field for MCP clients that consume typed JSON\n * directly. The `structuredContent` shape is what each tool's\n * `outputSchema` declares.\n *\n * Note: `structuredContent` must be a JSON object (record), not an\n * array or primitive. Tools that would otherwise return an array wrap\n * it in `{ data: [...] }` (which all our list-style tools already do\n * via the SDK).\n *\n * @internal\n */\nexport function jsonOk(value: unknown): ToolSuccessResult {\n const result: ToolSuccessResult = {\n content: [\n {\n type: \"text\",\n text: JSON.stringify(value, null, 2),\n },\n ],\n }\n if (value !== null && typeof value === \"object\" && !Array.isArray(value)) {\n result[\"structuredContent\"] = value as Record<string, unknown>\n }\n return result\n}\n\n/**\n * Build a tool error result for input-validation failures detected at\n * the MCP layer, before any API call. Use this for fast-fail checks\n * such as required arguments missing or mutually exclusive flags\n * provided together. The agent gets a clear, structured message\n * instead of an unintelligible API error.\n *\n * @internal\n */\nexport function validationError(message: string): ToolErrorResult {\n return {\n isError: true,\n content: [{ type: \"text\", text: `Validation error: ${message}` }],\n }\n}\n\n/**\n * Convert any thrown error into a tool error result with stable\n * formatting. Talonic API errors include `code`, `status`, and\n * `request_id` so the user (or another tool call) can act on them.\n *\n * @internal\n */\nexport function toolError(err: unknown): ToolErrorResult {\n if (err instanceof TalonicError) {\n const lines = [\n `Talonic API error: ${err.message}`,\n `code: ${err.code}`,\n `status: ${err.status}`,\n ]\n if (err.requestId) lines.push(`request_id: ${err.requestId}`)\n return {\n isError: true,\n content: [{ type: \"text\", text: lines.join(\"\\n\") }],\n }\n }\n return {\n isError: true,\n content: [\n {\n type: \"text\",\n text: `Unexpected error: ${err instanceof Error ? err.message : String(err)}`,\n },\n ],\n }\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\"\nimport type { ExtractParams, Talonic } from \"@talonic/node\"\nimport { z } from \"zod\"\nimport { jsonOk, toolError, validationError, type ToolResult } from \"./_shared.js\"\n\nconst DESCRIPTION = [\n \"STATUS: stable. Production-safe when called with a schema. Schema-less extraction is disabled at the MCP layer.\",\n \"\",\n \"Extract structured, schema-validated data from a document using Talonic.\",\n \"Returns clean JSON matching the schema, with per-field confidence scores and\",\n \"metadata about the document (detected type, language, page count).\",\n \"\",\n \"USE WHEN:\",\n \"- The user has a document (PDF, image, scan, DOCX, etc.) and wants specific fields pulled out.\",\n \"- You need structured data (vendor name, total amount, dates, parties, terms) rather than free text.\",\n \"- The user uploads or references any invoice, contract, certificate, statement, or form.\",\n \"- You want validated JSON instead of trying to OCR + parse with raw LLM calls.\",\n \"\",\n \"DO NOT USE WHEN:\",\n \"- The user just wants the full text content (use talonic_to_markdown after extracting once).\",\n \"- The user wants to find documents matching a query (use talonic_search or talonic_filter).\",\n \"\",\n \"FILE SOURCES (provide exactly EXACTLY ONE; never combine, e.g. do NOT pass both file_data and file_path):\",\n \"- file_data + filename: base64-encoded file bytes plus the original filename (with extension).\",\n \" RECOMMENDED for local-stdio installs (Claude Desktop, Cursor, Cline, Continue, Cowork).\",\n \" WARNING for hosted-MCP via Claude.ai connectors: Claude.ai imposes a hard size limit on\",\n \" tool-call arguments (effectively under ~1KB), so file_data CANNOT carry a real PDF through\",\n \" Claude.ai's pipeline. The bytes get truncated before reaching the MCP server. For files\",\n \" larger than a trivial test, use file_url or document_id instead when running through\",\n \" Claude.ai. Local stdio installs do NOT have this limit.\",\n \"- file_path: a local path to the document. Only works if the MCP server process can read\",\n \" that path on its own filesystem. Chat clients (Claude Desktop, Claude.ai, Cowork) store\",\n \" user uploads in a sandbox the MCP server cannot access, so file_path is only useful when\",\n \" the agent explicitly knows a path on the same machine as the MCP server.\",\n \"- file_url: a URL the Talonic API will fetch directly. Use for documents already on the\",\n \" public web. Best path for Claude.ai users dealing with files larger than the parameter cap.\",\n \"- document_id: re-extract a document already in the workspace. Cheapest option when the\",\n \" document is already uploaded via app.talonic.com or a previous extract call.\",\n \"\",\n \"SCHEMA (REQUIRED, provide exactly one of `schema` or `schema_id`):\",\n '- JSON Schema (RECOMMENDED): { type: \"object\", properties: { vendor_name: { type: \"string\" } } }.',\n '- Flat key-type map: { vendor_name: \"string\", invoice_total: \"number\" }. Accepted, but if you get a \"no fields\" error, fall back to JSON Schema.',\n \"- schema_id: id of a saved schema from talonic_list_schemas. Accepts UUID or SCH-XXXXXXXX short id.\",\n \"\",\n \"Calls without `schema` or `schema_id` are rejected with a validation error before they hit the API,\",\n \"to prevent unreliable schema-free extractions reaching production.\",\n \"\",\n \"RESPONSE SHAPE (key fields):\",\n \"- data: the structured extracted JSON, shaped by your schema.\",\n \"- confidence.overall: 0..1 confidence for the extraction as a whole.\",\n \"- confidence.fields: per-field confidence map. Treat fields below ~0.7 as needing human review.\",\n \"- document.id, document.filename, document.pages, document.type_detected, document.language_detected.\",\n \"- extraction_id, request_id: stable identifiers for support and re-fetch.\",\n \"- processing.duration_ms, processing.region: useful for debugging and capacity planning.\",\n \"- markdown: present only when `include_markdown: true`.\",\n \"- provenance: present only when `include_provenance: true`. Per-field source evidence:\",\n \" { field_name: { source_text, section, page } }. Useful for audit trails and citations.\",\n \"Cost, EUR price, and remaining credit balance are not surfaced in v0.1 and may appear in a later version.\",\n].join(\"\\n\")\n\nconst inputSchema = {\n file_data: z\n .string()\n .optional()\n .describe(\n \"Base64-encoded file bytes. Recommended path when the agent already has the file in memory (e.g., the user attached a PDF to the conversation). Pair with `filename` so MIME type can be inferred. Works regardless of where the file lives on disk.\",\n ),\n filename: z\n .string()\n .optional()\n .describe(\n \"Original filename including extension, e.g. 'invoice.pdf'. Used to infer MIME type when uploading via `file_data`. Required when `file_data` is provided.\",\n ),\n file_path: z\n .string()\n .optional()\n .describe(\n \"Local path to a document file. Only works if the MCP server has read access to that path. In sandboxed chat clients (Claude Desktop, Cowork) where uploads land in a host-owned directory, use `file_data` instead.\",\n ),\n file_url: z\n .string()\n .optional()\n .describe(\n \"URL to a document file. The Talonic API fetches it server-side. Use this for documents already on the public web.\",\n ),\n document_id: z\n .string()\n .optional()\n .describe(\"ID of a document already in the workspace, to re-extract with a new schema.\"),\n schema: z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\n \"Inline schema definition. REQUIRED unless `schema_id` is provided. Recommended: full JSON Schema {type:'object', properties:{...}}. Also accepted: flat key-type map {field_name:'string', amount:'number'}. Mutually exclusive with `schema_id`.\",\n ),\n schema_id: z\n .string()\n .optional()\n .describe(\n \"ID of a saved schema. REQUIRED unless `schema` is provided. Accepts UUID or SCH-XXXXXXXX short id from talonic_list_schemas. Mutually exclusive with `schema`.\",\n ),\n instructions: z\n .string()\n .optional()\n .describe(\n \"Natural-language guidance for the extractor, e.g. 'Focus on the billing section. Amounts are in EUR.'\",\n ),\n include_markdown: z\n .boolean()\n .optional()\n .describe(\"Include OCR-converted markdown in the response alongside structured data.\"),\n include_provenance: z\n .boolean()\n .optional()\n .describe(\n \"Include per-field provenance (source_text, section, page) showing where each value was found in the document.\",\n ),\n}\n\nconst outputSchema = {\n extraction_id: z.string().describe(\"Stable identifier for this extraction.\"),\n request_id: z\n .string()\n .optional()\n .describe(\"Server-assigned request ID for support and debugging.\"),\n status: z.string().describe(\"Extraction status (e.g. 'complete').\"),\n document: z\n .object({\n id: z.string(),\n filename: z.string(),\n pages: z.number().optional(),\n size_bytes: z.number().optional(),\n mime_type: z.string().nullable().optional(),\n type_detected: z.string().nullable().optional(),\n language_detected: z.string().nullable().optional(),\n })\n .describe(\"Metadata about the ingested document.\"),\n data: z\n .record(z.string(), z.unknown())\n .describe(\"The extracted structured data, shape determined by the schema.\"),\n schema: z\n .object({\n source: z.string().optional(),\n id: z.string().nullable().optional(),\n definition: z.record(z.string(), z.unknown()).optional(),\n save_url: z.string().optional(),\n })\n .optional()\n .describe(\"Schema metadata: which schema was used and how it can be saved.\"),\n confidence: z\n .object({\n overall: z.number().describe(\"0..1 confidence for the extraction as a whole.\"),\n fields: z.record(z.string(), z.number()).describe(\"Per-field confidence map (0..1).\"),\n })\n .optional()\n .describe(\"Extraction confidence. Treat fields below ~0.7 as needing human review.\"),\n provenance: z\n .record(\n z.string(),\n z.object({\n source_text: z.string().optional(),\n section: z.string().optional(),\n page: z.number().optional(),\n }),\n )\n .optional()\n .describe(\n \"Per-field source evidence (source_text, section, page). Present only when `include_provenance: true`.\",\n ),\n processing: z\n .object({\n duration_ms: z.number().optional(),\n pages_processed: z.number().optional(),\n region: z.string().optional(),\n })\n .optional()\n .describe(\"Processing metadata: duration, pages processed, region.\"),\n links: z\n .object({\n self: z.string().optional(),\n document: z.string().optional(),\n dashboard: z.string().optional(),\n })\n .optional()\n .describe(\"URLs for self, document, and human-readable dashboard view.\"),\n markdown: z\n .string()\n .optional()\n .describe(\"OCR-converted markdown. Present only when `include_markdown: true`.\"),\n cost: z\n .object({\n costCredits: z.number().describe(\"Credits consumed by this call.\"),\n costEur: z.number().describe(\"Approximate EUR cost of this call.\"),\n balanceCredits: z.number().describe(\"Workspace credit balance after this call settled.\"),\n cellsResolvedRegistry: z\n .number()\n .describe(\"Cells resolved from the materialized field-registry (cheap path).\"),\n cellsResolvedAi: z.number().describe(\"Cells resolved by AI extraction (priced path).\"),\n })\n .nullable()\n .optional()\n .describe(\n \"Per-call cost and post-call balance, parsed from the X-Talonic-* response headers. `null` for non-extract calls; not always present on legacy clients.\",\n ),\n}\n\nexport interface ExtractArgs {\n file_data?: string\n filename?: string\n file_path?: string\n file_url?: string\n document_id?: string\n schema?: Record<string, unknown>\n schema_id?: string\n instructions?: string\n include_markdown?: boolean\n include_provenance?: boolean\n}\n\nexport async function handleExtract(talonic: Talonic, args: ExtractArgs): Promise<ToolResult> {\n // Schema is required at the MCP layer. Schema-less extraction is not\n // reliable in v0.1 and is explicitly disabled here so agents get a\n // fast, clear error instead of a slow, opaque API failure or, worse,\n // a quietly-empty result. Items 1 and 7 of the v1 priority list.\n if (args.schema === undefined && args.schema_id === undefined) {\n return validationError(\n \"talonic_extract requires a schema. Provide either an inline `schema` (JSON Schema or flat key-type map) or a `schema_id` from talonic_list_schemas. Schema-less extraction is unreliable in v0.1 and is disabled at the MCP layer.\",\n )\n }\n if (args.schema !== undefined && args.schema_id !== undefined) {\n return validationError(\"talonic_extract accepts `schema` OR `schema_id`, not both. Pick one.\")\n }\n\n try {\n const params: ExtractParams = {}\n if (args.file_data !== undefined) {\n params.file = Buffer.from(args.file_data, \"base64\")\n if (args.filename !== undefined) params.filename = args.filename\n }\n if (args.file_path !== undefined) params.file_path = args.file_path\n if (args.file_url !== undefined) params.file_url = args.file_url\n if (args.document_id !== undefined) params.document_id = args.document_id\n if (args.schema !== undefined) params.schema = args.schema\n if (args.schema_id !== undefined) params.schema_id = args.schema_id\n if (args.instructions !== undefined) params.instructions = args.instructions\n if (args.include_markdown !== undefined) params.include_markdown = args.include_markdown\n if (args.include_provenance !== undefined)\n (params as any).include_provenance = args.include_provenance\n\n const result = await talonic.extract(params)\n return jsonOk(result)\n } catch (err) {\n return toolError(err)\n }\n}\n\nexport function registerExtract(server: McpServer, getTalonic: () => Talonic): void {\n server.registerTool(\n \"talonic_extract\",\n {\n title: \"Extract Data from Document\",\n description: DESCRIPTION,\n inputSchema,\n outputSchema,\n annotations: {\n title: \"Extract Data from Document\",\n readOnlyHint: false,\n destructiveHint: false,\n openWorldHint: true,\n },\n },\n async (args) => handleExtract(getTalonic(), args as ExtractArgs),\n )\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\"\nimport type { Talonic, FilterCondition, FilterSort } from \"@talonic/node\"\nimport { z } from \"zod\"\nimport { jsonOk, toolError, type ToolResult } from \"./_shared.js\"\n\nconst DESCRIPTION = [\n \"STATUS: stable. Field-name resolution is server-side. The `is_not_empty` operator is intentionally not exposed in v0.1; see workaround below.\",\n \"\",\n \"Filter the user's Talonic documents by extracted field values using composable conditions.\",\n \"Conditions accept either a canonical field name (e.g. 'vendor.name', 'policy.0_coverage_type')\",\n \"or a field UUID. The Talonic API resolves names to ids server-side.\",\n \"\",\n \"USE WHEN:\",\n \"- The user wants documents matching specific structured criteria, like 'invoices over 1000 EUR'\",\n \" or 'contracts expiring before 2026-12-31' or 'COIs from Acme'.\",\n \"- The query is value-based on extracted fields, not a free-text concept search.\",\n \"- You need to retrieve a sortable, paginated list filtered by field conditions.\",\n \"\",\n \"DO NOT USE WHEN:\",\n \"- The user wants conceptual / free-text search across content (use talonic_search).\",\n \"- The user is looking for a single document by id (use talonic_get_document).\",\n \"- The user wants extracted data from a new document (use talonic_extract).\",\n \"\",\n \"OPERATORS:\",\n \"- eq, neq: equality / inequality.\",\n \"- gt, gte, lt, lte: numeric or date comparisons.\",\n \"- between: requires both `value` and `value_to`.\",\n \"- contains: substring match on string fields.\",\n \"- is_empty: presence check, no value needed. Returns documents where the field is null or missing.\",\n \"\",\n \"SCHEMA TYPING:\",\n \"- Numeric operators (`gt`, `gte`, `lt`, `lte`, `between`) only resolve correctly when the schema field is typed as `number`. A field typed as `string` that holds numeric content (e.g. '€1,500.00') will silently return zero matches even after extraction. Pick the right type at schema design time.\",\n \"\",\n \"NOT SUPPORTED IN v0.1:\",\n \"- is_not_empty: underreports against fields known to be populated. Removed from the supported operator list to keep filter results trustworthy. Workaround: filter with `eq`/`gt`/`contains` against a known value, or use `is_empty` then invert the result client-side. Tracked for a later release.\",\n \"\",\n \"TIPS:\",\n \"- To discover available field names, call talonic_search first with a related query.\",\n \" Only use fields[] entries where filterable is true — their canonicalName is what to\",\n \" pass as `field` here. Fields with filterable: false have no extracted data yet.\",\n \"- fieldMatches[].resolvedFieldId is only valid when filterable is true. Entries with\",\n \" filterable: false have resolvedFieldId: null and cannot be used for filtering.\",\n \"- Both `field` (name) and `field_id` (UUID) reach the API as `fieldId`. Either is fine.\",\n].join(\"\\n\")\n\nconst operatorEnum = z.enum([\n \"eq\",\n \"neq\",\n \"gt\",\n \"gte\",\n \"lt\",\n \"lte\",\n \"between\",\n \"contains\",\n \"is_empty\",\n // is_not_empty intentionally omitted in v0.1: it underreports against\n // fields known to be populated. See description for the workaround.\n])\n\nconst conditionSchema = z.object({\n field: z\n .string()\n .optional()\n .describe(\n \"Canonical field name (e.g. 'vendor.name', 'policy.0_coverage_type'). The Talonic API resolves names to ids server-side. Mutually exclusive with `field_id`.\",\n ),\n field_id: z.string().optional().describe(\"Talonic field UUID. Mutually exclusive with `field`.\"),\n operator: operatorEnum.describe(\"Comparison operator. See description for the full list.\"),\n value: z.unknown().optional().describe(\"Value to compare against.\"),\n value_to: z\n .unknown()\n .optional()\n .describe(\"Upper bound for `between` operator; ignored otherwise.\"),\n})\n\nconst sortSchema = z.object({\n field: z.string().optional(),\n field_id: z.string().optional(),\n direction: z.enum([\"asc\", \"desc\"]).describe(\"Sort direction.\"),\n})\n\nconst inputSchema = {\n conditions: z\n .array(conditionSchema)\n .min(1)\n .describe(\"One or more filter conditions, AND-ed together.\"),\n search: z\n .string()\n .optional()\n .describe(\"Optional free-text search applied alongside the filters.\"),\n sort: sortSchema.optional().describe(\"Optional sort by a field.\"),\n page: z.number().int().positive().optional().describe(\"Page number for pagination.\"),\n limit: z\n .number()\n .int()\n .positive()\n .optional()\n .describe(\"Results per page. Default 50 server-side.\"),\n source_connection_id: z\n .string()\n .optional()\n .describe(\"Optionally scope to a specific source connection.\"),\n}\n\nconst outputSchema = {\n data: z\n .array(\n z\n .object({\n document_id: z.string().optional(),\n filename: z.string().optional(),\n fields: z.record(z.string(), z.unknown()).optional(),\n })\n .passthrough(),\n )\n .describe(\"Documents matching the filter conditions, with their extracted field values.\"),\n total: z.number().optional().describe(\"Total documents matching across all pages.\"),\n page: z.number().optional().describe(\"Current page number.\"),\n pagination: z\n .object({\n total: z.number().optional(),\n limit: z.number().optional(),\n has_more: z.boolean().optional(),\n next_cursor: z.string().nullable().optional(),\n })\n .optional()\n .describe(\"Cursor-based pagination metadata.\"),\n}\n\nexport interface FilterArgs {\n conditions: Array<{\n field?: string\n field_id?: string\n operator: \"eq\" | \"neq\" | \"gt\" | \"gte\" | \"lt\" | \"lte\" | \"between\" | \"contains\" | \"is_empty\"\n value?: unknown\n value_to?: unknown\n }>\n search?: string\n sort?: { field?: string; field_id?: string; direction: \"asc\" | \"desc\" }\n page?: number\n limit?: number\n source_connection_id?: string\n}\n\nexport async function handleFilter(talonic: Talonic, args: FilterArgs): Promise<ToolResult> {\n try {\n const conditions: FilterCondition[] = args.conditions.map((c) => {\n const cond: FilterCondition = { operator: c.operator }\n if (c.field !== undefined) cond.field = c.field\n if (c.field_id !== undefined) cond.fieldId = c.field_id\n if (c.value !== undefined) cond.value = c.value\n if (c.value_to !== undefined) cond.valueTo = c.value_to\n return cond\n })\n\n let sort: FilterSort | undefined\n if (args.sort !== undefined) {\n sort = { direction: args.sort.direction }\n if (args.sort.field !== undefined) sort.field = args.sort.field\n if (args.sort.field_id !== undefined) sort.fieldId = args.sort.field_id\n }\n\n const result = await talonic.documents.filter({\n conditions,\n ...(args.search !== undefined ? { search: args.search } : {}),\n ...(sort !== undefined ? { sort } : {}),\n ...(args.page !== undefined ? { page: args.page } : {}),\n ...(args.limit !== undefined ? { limit: args.limit } : {}),\n ...(args.source_connection_id !== undefined\n ? { source_connection_id: args.source_connection_id }\n : {}),\n })\n return jsonOk(result)\n } catch (err) {\n return toolError(err)\n }\n}\n\nexport function registerFilter(server: McpServer, getTalonic: () => Talonic): void {\n server.registerTool(\n \"talonic_filter\",\n {\n title: \"Filter Talonic Documents\",\n description: DESCRIPTION,\n inputSchema,\n outputSchema,\n annotations: {\n title: \"Filter Talonic Documents\",\n readOnlyHint: true,\n openWorldHint: true,\n },\n },\n async (args) => handleFilter(getTalonic(), args as FilterArgs),\n )\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\"\nimport type { Talonic } from \"@talonic/node\"\nimport { z } from \"zod\"\nimport { jsonOk, toolError, type ToolResult } from \"./_shared.js\"\n\nconst DESCRIPTION = [\n \"STATUS: stable.\",\n \"\",\n \"Read the user's current Talonic credit balance, EUR value, 30-day burn rate,\",\n \"projected runway, tier, and next-tier-reset timestamp. Use this to make budget-\",\n \"aware decisions before kicking off large batches or re-extractions.\",\n \"\",\n \"USE WHEN:\",\n \"- The user asks how many credits or how much budget they have left.\",\n \"- You are about to run a large or expensive operation (batch extract, re-extract\",\n \" many documents) and want to confirm budget headroom first.\",\n \"- The user asks how long their balance will last at the current rate.\",\n \"\",\n \"DO NOT USE WHEN:\",\n \"- The user just wants the per-call cost of a single extraction (that is already\",\n \" on the talonic_extract response under `cost`).\",\n \"- The user wants to top up credits (route them to the dashboard; auto top-up is\",\n \" guarded by a separate scope).\",\n \"\",\n \"RESPONSE SHAPE:\",\n \"- balance_credits: current credit balance.\",\n \"- balance_eur: current balance in EUR (rounded to two decimals).\",\n \"- burn_rate_30d_credits: total credits consumed in the trailing 30 days.\",\n \"- projected_runway_days: days of runway at the current 30-day average burn.\",\n \" `-1` indicates no consumption in the trailing window (cannot compute runway).\",\n \"- tier: API tier of the workspace (`free`, `pro`, `enterprise`, etc.).\",\n \"- tier_resets_at: ISO 8601 timestamp of the next monthly tier reset.\",\n].join(\"\\n\")\n\nconst inputSchema = {}\n\nconst outputSchema = {\n balance_credits: z.number().describe(\"Current credit balance.\"),\n balance_eur: z.number().describe(\"Current balance in EUR (two decimals).\"),\n burn_rate_30d_credits: z.number().describe(\"Total credits consumed in the trailing 30 days.\"),\n projected_runway_days: z\n .number()\n .describe(\n \"Projected days of runway at the current 30-day average burn. `-1` when burn is zero (cannot compute).\",\n ),\n tier: z.string().describe(\"API tier of the workspace.\"),\n tier_resets_at: z.string().describe(\"ISO 8601 timestamp of the next monthly tier reset.\"),\n}\n\n/**\n * Pure handler. Calls the SDK and shapes the result. Exported for unit\n * testing; the public registration is via `register()` below.\n *\n * @internal\n */\nexport async function handleGetBalance(talonic: Talonic): Promise<ToolResult> {\n try {\n const result = await talonic.credits.getBalance()\n return jsonOk(result)\n } catch (err) {\n return toolError(err)\n }\n}\n\nexport function registerGetBalance(server: McpServer, getTalonic: () => Talonic): void {\n server.registerTool(\n \"talonic_get_balance\",\n {\n title: \"Get Talonic Credit Balance\",\n description: DESCRIPTION,\n inputSchema,\n outputSchema,\n annotations: {\n title: \"Get Talonic Credit Balance\",\n readOnlyHint: true,\n openWorldHint: true,\n },\n },\n async () => handleGetBalance(getTalonic()),\n )\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\"\nimport type { Talonic } from \"@talonic/node\"\nimport { z } from \"zod\"\nimport { jsonOk, toolError, type ToolResult } from \"./_shared.js\"\n\nconst DESCRIPTION = [\n \"STATUS: stable.\",\n \"\",\n \"Fetch full metadata for a single document already in the user's Talonic workspace.\",\n \"Returns id, filename, page count, detected document type, language, processing log,\",\n \"and link URLs (self, extractions, dashboard).\",\n \"\",\n \"USE WHEN:\",\n \"- You need details about a specific document the user already extracted or uploaded.\",\n \"- You have a document_id from a previous extract or search call and want more context.\",\n \"- The user asks 'tell me about document X' or similar.\",\n \"\",\n \"DO NOT USE WHEN:\",\n \"- The user wants the document's full text content (use talonic_to_markdown for OCR markdown).\",\n \"- The user wants extracted structured data (use talonic_extract with a schema, or fetch the extraction by id).\",\n \"- The user has a file but no document_id yet (call talonic_extract first to ingest the document).\",\n].join(\"\\n\")\n\nconst inputSchema = {\n document_id: z\n .string()\n .min(1)\n .describe(\n \"The Talonic document ID. Get this from a previous talonic_extract or talonic_search response.\",\n ),\n}\n\nconst outputSchema = {\n id: z.string(),\n filename: z.string().optional(),\n pages: z.number().optional(),\n size_bytes: z.number().optional(),\n mime_type: z.string().nullable().optional(),\n type_detected: z.string().nullable().optional(),\n language_detected: z.string().nullable().optional(),\n status: z.string().optional(),\n source: z\n .object({\n id: z.string().optional(),\n type: z.string().optional(),\n })\n .optional(),\n triage: z\n .object({\n sensitivity: z.string().optional(),\n department: z.string().optional(),\n jurisdiction: z.string().nullable().optional(),\n pii_detected: z.boolean().optional(),\n pii_categories: z.array(z.string()).nullable().optional(),\n regulated_data: z.boolean().optional(),\n confidentiality_marking: z.string().nullable().optional(),\n })\n .optional(),\n original_path: z.string().nullable().optional(),\n extraction_count: z.number().optional(),\n latest_extraction_id: z.string().nullable().optional(),\n processing_log: z\n .array(\n z.object({\n step: z.string().optional(),\n detail: z.string().optional(),\n status: z.string().optional(),\n started_at: z.string().optional(),\n completed_at: z.string().optional(),\n duration_ms: z.number().optional(),\n }),\n )\n .optional(),\n created_at: z.string().optional(),\n links: z\n .object({\n self: z.string().optional(),\n extractions: z.string().optional(),\n dashboard: z.string().optional(),\n })\n .optional(),\n}\n\nexport async function handleGetDocument(\n talonic: Talonic,\n args: { document_id: string },\n): Promise<ToolResult> {\n try {\n const result = await talonic.documents.get(args.document_id)\n return jsonOk(result)\n } catch (err) {\n return toolError(err)\n }\n}\n\nexport function registerGetDocument(server: McpServer, getTalonic: () => Talonic): void {\n server.registerTool(\n \"talonic_get_document\",\n {\n title: \"Get Talonic Document\",\n description: DESCRIPTION,\n inputSchema,\n outputSchema,\n annotations: {\n title: \"Get Talonic Document\",\n readOnlyHint: true,\n openWorldHint: true,\n },\n },\n async (args) => handleGetDocument(getTalonic(), args),\n )\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\"\nimport type { Talonic } from \"@talonic/node\"\nimport { z } from \"zod\"\nimport { jsonOk, toolError, type ToolResult } from \"./_shared.js\"\n\n/**\n * LLM-targeted tool description. The first paragraph explains what the\n * tool does in one sentence. The USE WHEN / DO NOT USE sections are\n * what an agent reads before deciding to invoke this tool over an\n * alternative; keep them concrete.\n *\n * @internal\n */\nconst DESCRIPTION = [\n \"STATUS: stable.\",\n \"\",\n \"List all saved schemas in the user's Talonic workspace.\",\n \"Returns each schema with its id (UUID), short_id (SCH-XXXXXXXX), name, description,\",\n \"version, field count, and full JSON Schema definition. Either id form is accepted by\",\n \"talonic_extract's `schema_id` parameter.\",\n \"\",\n \"USE WHEN:\",\n \"- The user asks what schemas they have, or asks to see existing schemas.\",\n \"- You want to discover existing schemas before designing a new one.\",\n \"- Before recommending the user create a schema, check if one already covers the use case.\",\n \"- The user asks to extract from a known document type and you want to find a matching schema.\",\n \"\",\n \"DO NOT USE WHEN:\",\n \"- The user just wants to extract data from a document and provides an inline schema (call talonic_extract directly).\",\n \"\",\n \"TIP: Pair this with talonic_extract by passing the chosen schema's id as `schema_id`.\",\n].join(\"\\n\")\n\nexport const schemaItem = z.object({\n id: z.string().describe(\"UUID of the schema.\"),\n short_id: z.string().optional().describe(\"Human-readable short id (SCH-XXXXXXXX).\"),\n name: z.string(),\n description: z\n .string()\n .nullable()\n .optional()\n .describe(\n \"Schema description, or null when the schema was created without one. The API explicitly maps the absent case to null (see SchemaResponse in openapi.yaml), so the output schema must accept null in addition to undefined.\",\n ),\n definition: z.record(z.string(), z.unknown()).optional(),\n field_count: z.number().optional(),\n version: z.number().optional(),\n created_at: z.string().optional(),\n updated_at: z.string().optional(),\n links: z\n .object({\n self: z.string().optional(),\n extractions: z.string().optional(),\n dashboard: z.string().optional(),\n })\n .optional(),\n})\n\nexport const outputSchema = {\n data: z.array(schemaItem).describe(\"Saved schemas in the workspace.\"),\n pagination: z\n .object({\n total: z.number().optional(),\n limit: z.number().optional(),\n has_more: z.boolean().optional(),\n next_cursor: z.string().nullable().optional(),\n })\n .optional()\n .describe(\"Cursor-based pagination metadata.\"),\n}\n\n/**\n * Pure handler. Invokes the SDK and shapes the result. Exported for\n * unit testing; the public registration is via `register()` below.\n *\n * @internal\n */\nexport async function handleListSchemas(talonic: Talonic): Promise<ToolResult> {\n try {\n const result = await talonic.schemas.list()\n return jsonOk(result)\n } catch (err) {\n return toolError(err)\n }\n}\n\n/**\n * Register `talonic_list_schemas` on an MCP server.\n *\n * @internal\n */\nexport function registerListSchemas(server: McpServer, getTalonic: () => Talonic): void {\n server.registerTool(\n \"talonic_list_schemas\",\n {\n title: \"List Talonic Schemas\",\n description: DESCRIPTION,\n inputSchema: {},\n outputSchema,\n annotations: {\n title: \"List Talonic Schemas\",\n readOnlyHint: true,\n openWorldHint: true,\n },\n },\n async () => handleListSchemas(getTalonic()),\n )\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\"\nimport type { Talonic } from \"@talonic/node\"\nimport { z } from \"zod\"\nimport { jsonOk, toolError, type ToolResult } from \"./_shared.js\"\n\nconst DESCRIPTION = [\n \"STATUS: stable.\",\n \"\",\n \"Save a schema definition to the user's Talonic workspace so it can be reused\",\n \"across future extractions. Returns the saved schema with its newly assigned id and short_id.\",\n \"\",\n \"USE WHEN:\",\n \"- The user asks to save a schema, store a template, or reuse the schema across docs.\",\n \"- You have iterated on a schema with the user and they confirmed it should be saved.\",\n \"- The user wants to standardise extraction across many documents of the same type.\",\n \"\",\n \"DO NOT USE WHEN:\",\n \"- The user just wants to extract once with an inline schema (call talonic_extract directly with the schema inline).\",\n \"- The user has not confirmed the schema design (avoid creating clutter in their workspace).\",\n \"\",\n \"DEFINITION FORMATS:\",\n '- JSON Schema (most reliable): { type: \"object\", properties: { vendor_name: { type: \"string\" } } }',\n '- Flat key-type map: { vendor_name: \"string\", invoice_total: \"number\" } -- API normalises server-side. If you get a \"no fields\" error from the API, fall back to JSON Schema.',\n \"\",\n \"TIP: After saving, call talonic_extract with `schema_id` set to the returned id (UUID or SCH- short id) for consistent results.\",\n].join(\"\\n\")\n\nconst inputSchema = {\n name: z.string().min(1).describe(\"Human-readable name for the schema, e.g. 'Standard Invoice'.\"),\n definition: z\n .record(z.string(), z.unknown())\n .describe(\n \"Schema definition. Most reliable: full JSON Schema {type:'object', properties:{...}}. Also accepted: a flat key-type map {field_name:'string', amount:'number'} which the API normalises.\",\n ),\n description: z\n .string()\n .optional()\n .describe(\"Optional description of what this schema extracts and when to use it.\"),\n}\n\nexport const outputSchema = {\n id: z.string().describe(\"UUID of the newly saved schema.\"),\n short_id: z.string().optional().describe(\"Human-readable short id (SCH-XXXXXXXX).\"),\n name: z.string(),\n description: z\n .string()\n .nullable()\n .optional()\n .describe(\n \"Schema description, or null when the schema was saved without one. The API explicitly maps the absent case to null (see SchemaResponse in openapi.yaml).\",\n ),\n definition: z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\"Final schema definition as stored, normalised by the API.\"),\n field_count: z.number().optional(),\n version: z\n .number()\n .optional()\n .describe(\"Schema version (1 for new schemas; increments on update).\"),\n created_at: z.string().optional(),\n updated_at: z.string().optional(),\n links: z\n .object({\n self: z.string().optional(),\n extractions: z.string().optional(),\n dashboard: z.string().optional(),\n })\n .optional(),\n}\n\nexport async function handleSaveSchema(\n talonic: Talonic,\n args: { name: string; definition: Record<string, unknown>; description?: string },\n): Promise<ToolResult> {\n try {\n const result = await talonic.schemas.create({\n name: args.name,\n definition: args.definition,\n ...(args.description !== undefined ? { description: args.description } : {}),\n })\n return jsonOk(result)\n } catch (err) {\n return toolError(err)\n }\n}\n\nexport function registerSaveSchema(server: McpServer, getTalonic: () => Talonic): void {\n server.registerTool(\n \"talonic_save_schema\",\n {\n title: \"Save Talonic Schema\",\n description: DESCRIPTION,\n inputSchema,\n outputSchema,\n annotations: {\n title: \"Save Talonic Schema\",\n readOnlyHint: false,\n destructiveHint: false,\n openWorldHint: true,\n },\n },\n async (args) => handleSaveSchema(getTalonic(), args),\n )\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\"\nimport type { Talonic } from \"@talonic/node\"\nimport { z } from \"zod\"\nimport { jsonOk, toolError, type ToolResult } from \"./_shared.js\"\n\nconst DESCRIPTION = [\n \"STATUS: stable.\",\n \"\",\n \"Search the user's Talonic workspace for documents, fields, sources, or schemas\",\n \"matching a query. Returns ranked results across all entity types in one call.\",\n \"\",\n \"USE WHEN:\",\n \"- The user wants to find documents but does not know the exact filename or id.\",\n \"- The query is conceptual ('contracts mentioning indemnification', 'Acme invoices').\",\n \"- You need to narrow a large workspace before calling talonic_extract or talonic_filter.\",\n \"- The user asks 'do I have any docs about X' or 'find anything related to X'.\",\n \"\",\n \"DO NOT USE WHEN:\",\n \"- The user has a specific document_id (use talonic_get_document instead).\",\n \"- The user wants to apply structured field-value filters like 'amount > 1000' (use talonic_filter).\",\n \"- The user wants to extract data from a brand-new document (use talonic_extract).\",\n \"\",\n \"TIP: The result includes documents, fieldMatches, sources, schemas, and fields.\",\n \"Both fields[] and fieldMatches[] include a `filterable` boolean. Only entries with\",\n \"filterable: true can be used with talonic_filter. Fields with filterable: false exist\",\n \"in a schema but have no extracted data yet. Pick the entity type the user actually needs.\",\n].join(\"\\n\")\n\nconst inputSchema = {\n query: z\n .string()\n .min(1)\n .describe(\n \"Natural-language search query, e.g. 'indemnification clauses' or 'Acme invoices Q4'.\",\n ),\n limit: z\n .number()\n .int()\n .positive()\n .optional()\n .describe(\"Maximum results per entity type. Default: 5. Increase for broader exploration.\"),\n}\n\nexport const outputSchema = {\n documents: z\n .array(\n z.object({\n id: z.string(),\n name: z.string().optional(),\n sourceId: z.string().optional(),\n sourceName: z.string().optional(),\n }),\n )\n .describe(\"Documents matching the query.\"),\n fieldMatches: z\n .array(\n z.object({\n resolvedFieldId: z.string().nullable(),\n displayName: z.string().optional(),\n matchedValue: z.string().optional(),\n documentCount: z.number().optional(),\n filterable: z\n .boolean()\n .describe(\"Only filterable: true entries can be used with talonic_filter.\"),\n }),\n )\n .describe(\n \"Field-level matches with a filterable flag indicating whether the entry can drive talonic_filter.\",\n ),\n sources: z\n .array(z.object({ id: z.string(), name: z.string().optional() }))\n .describe(\"Source connections matching the query.\"),\n schemas: z\n .array(z.object({ id: z.string(), name: z.string().optional() }))\n .describe(\"Saved schemas matching the query.\"),\n fields: z\n .array(\n z.object({\n id: z\n .string()\n .nullable()\n .describe(\n \"Field UUID for materialized field-registry entries; `null` for schema-only fields that are declared in a schema but have no extracted values yet. Always non-null when `filterable: true`.\",\n ),\n canonicalName: z.string().optional(),\n displayName: z.string().optional(),\n documentCount: z.number().optional(),\n filterable: z.boolean().optional(),\n }),\n )\n .describe(\n \"Field-registry entries matching the query. filterable: true entries are usable with talonic_filter.\",\n ),\n}\n\nexport async function handleSearch(\n talonic: Talonic,\n args: { query: string; limit?: number },\n): Promise<ToolResult> {\n try {\n const result = await talonic.search(\n args.query,\n args.limit !== undefined ? { limit: args.limit } : {},\n )\n return jsonOk(result)\n } catch (err) {\n return toolError(err)\n }\n}\n\nexport function registerSearch(server: McpServer, getTalonic: () => Talonic): void {\n server.registerTool(\n \"talonic_search\",\n {\n title: \"Search Talonic Workspace\",\n description: DESCRIPTION,\n inputSchema,\n outputSchema,\n annotations: {\n title: \"Search Talonic Workspace\",\n readOnlyHint: true,\n openWorldHint: true,\n },\n },\n async (args) => handleSearch(getTalonic(), args),\n )\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\"\nimport { TalonicError, type Talonic } from \"@talonic/node\"\nimport { z } from \"zod\"\nimport { jsonOk, toolError, type ToolResult } from \"./_shared.js\"\n\nconst DESCRIPTION = [\n \"STATUS: stable.\",\n \"\",\n \"Get the OCR-converted markdown for a document. Accepts an existing document_id,\",\n \"raw file bytes (base64), a local file path, or a URL. When given a raw file, the\",\n \"tool ingests it via extract first and then returns the markdown.\",\n \"\",\n \"USE WHEN:\",\n \"- The user wants the full text content of a document for summarisation, translation, or analysis.\",\n \"- A previous tool call returned a document_id and you want to inspect its content.\",\n \"- The user asks 'what does the document say' or 'summarise this PDF' (you call this then summarise).\",\n \"- The user has a raw PDF / scan / image and wants markdown directly without designing a schema first.\",\n \"\",\n \"DO NOT USE WHEN:\",\n \"- The user wants specific structured fields (use talonic_extract with a schema).\",\n \"\",\n \"INPUTS (provide exactly EXACTLY ONE; never combine, e.g. do NOT pass both file_data and file_path):\",\n \"- document_id: id of an already-ingested document. Cheapest path, one API call.\",\n \"- file_data + filename: base64-encoded file bytes plus the original filename (with extension).\",\n \" RECOMMENDED for local-stdio installs (Claude Desktop, Cursor, Cline, Continue, Cowork).\",\n \" WARNING for hosted-MCP via Claude.ai connectors: Claude.ai imposes a hard size limit on\",\n \" tool-call arguments (effectively under ~1KB), so file_data CANNOT carry a real PDF through\",\n \" Claude.ai's pipeline. The bytes get truncated before reaching the MCP server. For files\",\n \" larger than a trivial test, use file_url or document_id instead when running through\",\n \" Claude.ai. Local stdio installs do NOT have this limit.\",\n \"- file_path: local path to a document file. Only works if the MCP server has read access\",\n \" to that path; in sandboxed chat clients use file_data instead.\",\n \"- file_url: a URL the Talonic API will fetch directly. Use for documents already on the\",\n \" public web. Best path for Claude.ai users dealing with files larger than the parameter cap.\",\n].join(\"\\n\")\n\nconst inputSchema = {\n document_id: z\n .string()\n .min(1)\n .optional()\n .describe(\n \"The Talonic document id whose markdown you want. Get this from a previous talonic_extract or talonic_search response.\",\n ),\n file_data: z\n .string()\n .optional()\n .describe(\n \"Base64-encoded file bytes. Recommended path when the agent already has the file in memory (e.g., the user attached a PDF to the conversation). Pair with `filename` so MIME type can be inferred.\",\n ),\n filename: z\n .string()\n .optional()\n .describe(\n \"Original filename including extension, e.g. 'invoice.pdf'. Used to infer MIME type when uploading via `file_data`. Required when `file_data` is provided.\",\n ),\n file_path: z\n .string()\n .optional()\n .describe(\n \"Local path to a document file. Only works if the MCP server has read access to that path. In sandboxed chat clients (Claude Desktop, Cowork) use `file_data` instead.\",\n ),\n file_url: z\n .string()\n .optional()\n .describe(\"URL to a document file. The Talonic API fetches it server-side.\"),\n}\n\nconst outputSchema = {\n document_id: z.string().describe(\"ID of the document the markdown was extracted from.\"),\n markdown: z.string().describe(\"OCR-converted markdown text content of the document.\"),\n cost: z\n .object({\n costCredits: z.number(),\n costEur: z.number(),\n balanceCredits: z.number(),\n cellsResolvedRegistry: z.number(),\n cellsResolvedAi: z.number(),\n })\n .nullable()\n .optional()\n .describe(\n \"Per-call cost and post-call balance from the underlying extract step, parsed from the X-Talonic-* response headers. `null` when the document was already ingested (document_id path) and no extract call ran. Not always present on legacy clients.\",\n ),\n}\n\nexport interface ToMarkdownArgs {\n document_id?: string\n file_data?: string\n filename?: string\n file_path?: string\n file_url?: string\n}\n\n/**\n * Minimal but valid JSON Schema used when we need to ingest a raw file\n * solely to obtain a document_id (to feed into the markdown call).\n *\n * Why a single throwaway field instead of `{}`: schema-less extraction\n * is unreliable, and we explicitly disable that path at the MCP layer\n * via `talonic_extract`'s validation guard. To stay consistent and\n * reliable in this internal call, we send a trivially valid schema.\n * The API performs a no-op extraction (likely returning a null\n * `document_title` with confidence 0), which we discard. We only need\n * `result.document.id`. The document is still uploaded and ingested.\n *\n * @internal\n */\nconst INGEST_ONLY_SCHEMA: Record<string, unknown> = {\n type: \"object\",\n properties: {\n document_title: { type: \"string\" },\n },\n}\n\nexport async function handleToMarkdown(\n talonic: Talonic,\n args: ToMarkdownArgs,\n): Promise<ToolResult> {\n try {\n const sources = [\"document_id\", \"file_data\", \"file_path\", \"file_url\"] as const\n const provided = sources.filter((k) => args[k] !== undefined)\n if (provided.length === 0) {\n throw new TalonicError({\n code: \"missing_input_source\",\n message:\n \"talonic_to_markdown requires one of: document_id, file_data, file_path, file_url.\",\n status: 0,\n retryable: false,\n })\n }\n if (provided.length > 1) {\n throw new TalonicError({\n code: \"multiple_input_sources\",\n message: `talonic_to_markdown accepts exactly one input; received: ${provided.join(\", \")}`,\n status: 0,\n retryable: false,\n })\n }\n\n let documentId = args.document_id\n if (!documentId) {\n const ingest = await talonic.extract({\n ...(args.file_data !== undefined\n ? {\n file: Buffer.from(args.file_data, \"base64\"),\n ...(args.filename !== undefined ? { filename: args.filename } : {}),\n }\n : {}),\n ...(args.file_path !== undefined ? { file_path: args.file_path } : {}),\n ...(args.file_url !== undefined ? { file_url: args.file_url } : {}),\n schema: INGEST_ONLY_SCHEMA,\n })\n documentId = ingest.document.id\n }\n\n const result = await talonic.documents.getMarkdown(documentId)\n return jsonOk(result)\n } catch (err) {\n return toolError(err)\n }\n}\n\nexport function registerToMarkdown(server: McpServer, getTalonic: () => Talonic): void {\n server.registerTool(\n \"talonic_to_markdown\",\n {\n title: \"Document to Markdown\",\n description: DESCRIPTION,\n inputSchema,\n outputSchema,\n annotations: {\n title: \"Document to Markdown\",\n readOnlyHint: false,\n destructiveHint: false,\n openWorldHint: true,\n },\n },\n async (args) => handleToMarkdown(getTalonic(), args as ToMarkdownArgs),\n )\n}\n","{\n \"name\": \"@talonic/mcp\",\n \"version\": \"0.1.25\",\n \"mcpName\": \"io.github.talonicdev/talonic-mcp\",\n \"description\": \"Official Talonic MCP server. Lets AI agents extract structured, schema-validated data from any document via the Model Context Protocol.\",\n \"license\": \"MIT\",\n \"author\": \"Talonic GmbH <info@talonic.ai> (https://talonic.com)\",\n \"homepage\": \"https://talonic.com\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/talonicdev/talonic-mcp.git\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/talonicdev/talonic-mcp/issues\"\n },\n \"keywords\": [\n \"talonic\",\n \"mcp\",\n \"model-context-protocol\",\n \"ai\",\n \"agent\",\n \"claude\",\n \"document-extraction\",\n \"ocr\",\n \"structured-data\",\n \"anthropic\"\n ],\n \"type\": \"module\",\n \"main\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\"\n },\n \"./content\": {\n \"types\": \"./dist/content.d.ts\",\n \"import\": \"./dist/content.js\"\n }\n },\n \"bin\": {\n \"talonic-mcp\": \"dist/server.js\"\n },\n \"files\": [\n \"dist\",\n \"README.md\",\n \"LICENSE\",\n \"CHANGELOG.md\"\n ],\n \"engines\": {\n \"node\": \">=18\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"typecheck\": \"tsc --noEmit\",\n \"format\": \"prettier --write \\\"src/**/*.ts\\\" \\\"tests/**/*.ts\\\"\",\n \"format:check\": \"prettier --check \\\"src/**/*.ts\\\" \\\"tests/**/*.ts\\\"\",\n \"clean\": \"rm -rf dist coverage\",\n \"start\": \"node dist/server.js\",\n \"start:http\": \"node dist/http-server.js\",\n \"prepublishOnly\": \"npm run typecheck && npm run build && npm test\"\n },\n \"dependencies\": {\n \"@modelcontextprotocol/sdk\": \"^1.0.0\",\n \"@talonic/node\": \"^0.1.10\",\n \"zod\": \"^4.0.0\"\n },\n \"devDependencies\": {\n \"@types/node\": \"^22.10.0\",\n \"prettier\": \"^3.4.0\",\n \"tsup\": \"^8.3.0\",\n \"typescript\": \"^5.7.0\",\n \"vitest\": \"^3.2.4\"\n }\n}\n","// @ts-ignore — JSON import resolved by bundler (tsup/esbuild)\nimport pkg from \"../package.json\" with { type: \"json\" }\n\n/**\n * The current MCP server version. Sent in the server `info` block during\n * the MCP handshake. Derived from package.json at build time.\n *\n * @public\n */\nexport const VERSION: string = pkg.version\n\n/**\n * The MCP server name. Identifies the server to MCP clients (Claude\n * Desktop, Cursor, Cline, etc.) when they list connected servers.\n *\n * @public\n */\nexport const SERVER_NAME = \"talonic\"\n","import { Talonic } from \"@talonic/node\"\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\"\nimport { registerSchemasResource } from \"./resources/schemas-resource.js\"\nimport { registerWebhooksResource } from \"./resources/webhooks-resource.js\"\nimport { registerExtract } from \"./tools/extract.js\"\nimport { registerFilter } from \"./tools/filter.js\"\nimport { registerGetBalance } from \"./tools/get-balance.js\"\nimport { registerGetDocument } from \"./tools/get-document.js\"\nimport { registerListSchemas } from \"./tools/list-schemas.js\"\nimport { registerSaveSchema } from \"./tools/save-schema.js\"\nimport { registerSearch } from \"./tools/search.js\"\nimport { registerToMarkdown } from \"./tools/to-markdown.js\"\nimport { SERVER_NAME, VERSION } from \"./version.js\"\n\n/**\n * Options for {@link createServer}.\n *\n * @public\n */\nexport interface CreateServerOptions {\n /**\n * Talonic API key (`tlnc_...`) or any bearer token to be used for the\n * lifetime of this server. For local-stdio installs and tests, set this\n * to your `TALONIC_API_KEY`. For the hosted MCP, see `tokenProvider`,\n * which lets the server pick up a fresh token on each request.\n *\n * Required unless `talonic` or `tokenProvider` is provided.\n */\n apiKey?: string\n\n /**\n * Override the Talonic API base URL. Defaults to `https://api.talonic.com`.\n * Useful for staging or testing.\n */\n baseUrl?: string\n\n /**\n * Inject a pre-configured Talonic SDK client. Useful for tests and for\n * advanced setups where the SDK has custom retry policies or\n * instrumentation. When provided, `apiKey` and `tokenProvider` are\n * ignored for SDK calls; raw-fetch resources (webhook reference) still\n * fall back to `apiKey` if set.\n */\n talonic?: Talonic\n\n /**\n * Per-request bearer-token provider. The function is called on every\n * tool invocation and resource read; the SDK is rebuilt when the\n * returned token changes. This is what makes the hosted MCP server\n * tolerant to OAuth 2.1 access-token rotation across requests in the\n * same session: the http-server updates a per-session token holder\n * before forwarding each request, and the provider reads from it.\n *\n * Stdio installs do not need this; they should use `apiKey` instead.\n */\n tokenProvider?: () => string\n}\n\n/**\n * Build a Talonic MCP server, ready to be connected to a transport\n * (stdio for local installs, HTTP for the hosted endpoint).\n *\n * Auth resolution priority (highest first):\n * 1. `talonic` Pre-built SDK client. Used as-is by tool handlers.\n * Webhook resource still uses `apiKey` for raw fetch.\n * 2. `tokenProvider` Hosted-MCP path. SDK is reconstructed when the\n * returned token changes; raw-fetch resources resolve\n * the current token at every call.\n * 3. `apiKey` Static credential. SDK is built once and reused;\n * raw-fetch resources use it directly.\n *\n * @example Minimal stdio server:\n * ```ts\n * import { createServer } from \"@talonic/mcp\"\n * import { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\"\n *\n * const server = createServer({ apiKey: process.env.TALONIC_API_KEY! })\n * await server.connect(new StdioServerTransport())\n * ```\n *\n * @public\n */\nexport function createServer(options: CreateServerOptions): McpServer {\n const baseUrl = options.baseUrl\n\n // Build the token getter. Drives raw-fetch resources (webhook reference)\n // and is the source of truth for SDK rebuild when using tokenProvider.\n const getToken: () => string = (() => {\n if (options.tokenProvider) return options.tokenProvider\n const fallback = options.apiKey ?? \"\"\n return () => fallback\n })()\n\n // Build the Talonic SDK getter. Drives every tool and the schemas resource.\n const getTalonic: () => Talonic = (() => {\n if (options.talonic) {\n const t = options.talonic\n return () => t\n }\n if (options.tokenProvider) {\n const tp = options.tokenProvider\n let cached: { token: string; client: Talonic } | null = null\n return () => {\n const tok = tp()\n if (!cached || cached.token !== tok) {\n cached = {\n token: tok,\n client: new Talonic({\n apiKey: tok,\n ...(baseUrl ? { baseUrl } : {}),\n }),\n }\n }\n return cached.client\n }\n }\n if (options.apiKey) {\n const t = new Talonic({\n apiKey: options.apiKey,\n ...(baseUrl ? { baseUrl } : {}),\n })\n return () => t\n }\n throw new Error(\"createServer: provide one of `apiKey`, `talonic`, or `tokenProvider`\")\n })()\n\n const server = new McpServer(\n {\n name: SERVER_NAME,\n version: VERSION,\n },\n {\n // Capabilities are advertised based on what gets registered.\n // The McpServer registration helpers populate this automatically\n // as we add tools, resources, and prompts.\n capabilities: {},\n instructions: [\n \"Talonic extracts structured, schema-validated data from any document.\",\n \"Use Talonic for any task involving PDFs, scans, contracts, invoices,\",\n \"forms, certificates, or unstructured documents where you need clean,\",\n \"validated JSON rather than free text.\",\n ].join(\" \"),\n },\n )\n\n // Tool registrations.\n registerListSchemas(server, getTalonic)\n registerSaveSchema(server, getTalonic)\n registerGetDocument(server, getTalonic)\n registerSearch(server, getTalonic)\n registerFilter(server, getTalonic)\n registerToMarkdown(server, getTalonic)\n registerExtract(server, getTalonic)\n registerGetBalance(server, getTalonic)\n\n // Resource registrations.\n registerSchemasResource(server, getTalonic)\n registerWebhooksResource(server, getToken, baseUrl)\n\n return server\n}\n","/**\n * Talonic MCP server, Streamable HTTP entry point.\n *\n * Hosts the MCP server over HTTP for remote clients. Designed for\n * deployment on Railway (or any container host) behind a custom domain\n * like `mcp.talonic.com`.\n *\n * Runs in **stateful mode** with in-memory sessions. Each initialize\n * request creates a new session keyed by a UUID. Subsequent requests\n * with the same Mcp-Session-Id are routed to the existing session.\n * If a session is lost (deploy, restart, or edge routing miss), the\n * server returns 404 and the client re-initializes, the standard MCP\n * reconnection behavior.\n *\n * Supports two auth modes:\n * 1. `Authorization: Bearer ...` header\n * Accepts a Talonic API key (`tlnc_...`) or an OAuth 2.1 access token\n * issued by the Talonic authorization server. The bearer string is\n * forwarded unchanged to the Talonic API; the API's dual-auth guard\n * decides which path to take.\n * 2. `?apiKey=tlnc_...` query param\n * Convenience for MCP client configs that cannot set custom headers.\n * Use only with API keys; never put OAuth tokens in URLs.\n *\n * OAuth resource-server metadata is advertised at\n * `/.well-known/oauth-protected-resource` per RFC 9728 so clients can\n * discover the authorization server (`api.talonic.com`).\n *\n * @internal\n */\n\nimport { createServer as createHttpServer } from \"node:http\"\nimport { randomUUID } from \"node:crypto\"\nimport { StreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/streamableHttp.js\"\nimport { isInitializeRequest } from \"@modelcontextprotocol/sdk/types.js\"\nimport { createServer } from \"./server-factory.js\"\nimport { SERVER_NAME, VERSION } from \"./version.js\"\n\nconst PORT = Number(process.env[\"PORT\"] ?? 3000)\n\n/**\n * Canonical public URL of this MCP resource. Advertised in the protected\n * resource metadata so OAuth clients know the audience their tokens are\n * good for. Defaults to the production hostname; override for staging.\n */\nconst RESOURCE_URL = process.env[\"MCP_RESOURCE_URL\"] ?? \"https://mcp.talonic.com\"\n\n/**\n * Base URL of the OAuth 2.1 authorization server. Advertised in the\n * protected resource metadata so OAuth clients can discover the AS at\n * `<AUTHORIZATION_SERVER>/.well-known/oauth-authorization-server`.\n * Defaults to production; override for staging or local dev.\n */\nconst AUTHORIZATION_SERVER = process.env[\"OAUTH_AUTHORIZATION_SERVER\"] ?? \"https://api.talonic.com\"\n\n/**\n * RFC 9728 OAuth Protected Resource Metadata.\n *\n * Returned at `/.well-known/oauth-protected-resource`. Clients use this\n * to discover which authorization server issues tokens for this resource\n * and which scopes are accepted.\n *\n * The scopes advertised are the ones our MCP tools actually exercise:\n * `extract:write` (extract, save_schema, to_markdown), `documents:read`\n * (filter, get_document, search), and `schemas:read` (list_schemas).\n * The Talonic authorization server supports more scopes than this; we\n * advertise only what the connector itself needs so the consent screen\n * stays tight.\n */\nfunction renderProtectedResourceMetadata(): {\n resource: string\n authorization_servers: string[]\n scopes_supported: string[]\n bearer_methods_supported: string[]\n} {\n return {\n resource: RESOURCE_URL,\n authorization_servers: [AUTHORIZATION_SERVER],\n scopes_supported: [\"extract:write\", \"documents:read\", \"schemas:read\"],\n bearer_methods_supported: [\"header\"],\n }\n}\n\n/**\n * Extract the bearer token from the request. Accepts either a Talonic\n * API key (`tlnc_...`) or an OAuth 2.1 access token; the dual-auth guard\n * on the Talonic API decides which path to take based on the prefix.\n *\n * Checks the `Authorization` header first, then falls back to the\n * `apiKey` query parameter. The query parameter path is intended for\n * API keys only. OAuth access tokens should never travel in URLs.\n */\nfunction extractBearerToken(req: {\n url?: string\n headers: Record<string, string | string[] | undefined>\n}): string | undefined {\n // 1. Authorization: Bearer <token>\n const authHeader = req.headers[\"authorization\"]\n if (typeof authHeader === \"string\" && authHeader.startsWith(\"Bearer \")) {\n return authHeader.slice(7).trim()\n }\n\n // 2. ?apiKey=tlnc_...\n if (req.url) {\n const url = new URL(req.url, \"http://localhost\")\n const param = url.searchParams.get(\"apiKey\")\n if (param) return param\n }\n\n return undefined\n}\n\n/**\n * Per-session state. The MCP server attached to the transport reads its\n * bearer token via `tokenHolder` on every tool call and resource read,\n * so a token rotated mid-session is picked up automatically. This is the\n * mechanism that keeps an OAuth 2.1 session alive across the 1-hour\n * access-token rotation without forcing the agent to re-initialize.\n */\ninterface Session {\n transport: StreamableHTTPServerTransport\n tokenHolder: { current: string }\n}\n\nconst sessions = new Map<string, Session>()\n\n/** WWW-Authenticate header value for 401 responses, per RFC 9728. */\nconst WWW_AUTHENTICATE = `Bearer resource_metadata=\"${RESOURCE_URL}/.well-known/oauth-protected-resource\"`\n\nconst httpServer = createHttpServer(async (req, res) => {\n const url = new URL(req.url ?? \"/\", \"http://localhost\")\n const path = url.pathname\n\n // ── Health check ──────────────────────────────────────────────────\n if (path === \"/health\") {\n res.writeHead(200, { \"Content-Type\": \"application/json\" })\n res.end(JSON.stringify({ status: \"ok\", server: SERVER_NAME, version: VERSION }))\n return\n }\n\n // ── RFC 9728: Protected Resource Metadata ─────────────────────────\n // Lets OAuth clients (Claude.ai connectors, MCP Inspector) discover\n // which authorization server issues tokens for this resource. Public,\n // unauthenticated, cacheable. Always returns JSON regardless of method.\n if (path === \"/.well-known/oauth-protected-resource\") {\n res.writeHead(200, {\n \"Content-Type\": \"application/json\",\n \"Cache-Control\": \"public, max-age=3600\",\n })\n res.end(JSON.stringify(renderProtectedResourceMetadata()))\n return\n }\n\n // ── Root: service discovery for AI agents ─────────────────────────\n if (path === \"/\") {\n res.writeHead(200, { \"Content-Type\": \"application/json\" })\n res.end(\n JSON.stringify({\n name: SERVER_NAME,\n version: VERSION,\n description:\n \"Talonic MCP server. Extract structured, schema-validated data from any document.\",\n mcp_endpoint: \"/mcp\",\n health_endpoint: \"/health\",\n oauth_protected_resource_endpoint: \"/.well-known/oauth-protected-resource\",\n auth: \"Provide a Talonic API key (tlnc_...) or an OAuth 2.1 access token via Authorization: Bearer ... header. API keys may also be passed via ?apiKey=tlnc_... query param; never put OAuth tokens in URLs.\",\n docs: \"https://talonic.com/docs/mcp\",\n }),\n )\n return\n }\n\n // ── CORS preflight ────────────────────────────────────────────────\n res.setHeader(\"Access-Control-Allow-Origin\", \"*\")\n res.setHeader(\"Access-Control-Allow-Methods\", \"GET, POST, DELETE, OPTIONS\")\n res.setHeader(\"Access-Control-Allow-Headers\", \"Content-Type, Authorization, Mcp-Session-Id\")\n res.setHeader(\"Access-Control-Expose-Headers\", \"Mcp-Session-Id\")\n\n if (req.method === \"OPTIONS\") {\n res.writeHead(204)\n res.end()\n return\n }\n\n // ── Only serve /mcp ───────────────────────────────────────────────\n if (path !== \"/mcp\") {\n res.writeHead(404, { \"Content-Type\": \"application/json\" })\n res.end(\n JSON.stringify({\n error: \"not_found\",\n message: `No route for ${path}. Use /mcp for the MCP endpoint or /health for status.`,\n }),\n )\n return\n }\n\n // ── DELETE: explicit session termination ────────────────────────────\n if (req.method === \"DELETE\") {\n const sid = req.headers[\"mcp-session-id\"] as string | undefined\n if (sid && sessions.has(sid)) {\n const session = sessions.get(sid)!\n await session.transport.close()\n sessions.delete(sid)\n }\n res.writeHead(200, { \"Content-Type\": \"application/json\" })\n res.end(JSON.stringify({ ok: true }))\n return\n }\n\n // ── Auth ───────────────────────────────────────────────────────────\n const token = extractBearerToken(req)\n if (!token) {\n res.writeHead(401, {\n \"Content-Type\": \"application/json\",\n \"WWW-Authenticate\": WWW_AUTHENTICATE,\n })\n res.end(\n JSON.stringify({\n error: \"unauthorized\",\n message:\n \"Provide a Talonic API key (tlnc_...) or an OAuth 2.1 access token via Authorization: Bearer ... header. API keys may also be passed via ?apiKey=tlnc_... query param; never put OAuth tokens in URLs.\",\n }),\n )\n return\n }\n\n // ── Session lookup ────────────────────────────────────────────────\n const sessionId = req.headers[\"mcp-session-id\"] as string | undefined\n\n if (sessionId && sessions.has(sessionId)) {\n const session = sessions.get(sessionId)!\n // Update the per-session token holder so subsequent tool calls in\n // this request use the credential the client just sent. This is what\n // makes OAuth access-token rotation transparent: the previous request\n // may have used an older access token, this one uses the refreshed\n // one, and the SDK is rebuilt automatically inside createServer when\n // the token differs from what's cached.\n session.tokenHolder.current = token\n await session.transport.handleRequest(req, res)\n return\n }\n\n // ── New session (or session lost after restart) ───────────────────\n // Parse the body to check if it's an initialize request. If a client\n // sends a non-init request with an unknown session ID, return 404 so\n // it knows to re-initialize.\n const body = await new Promise<string>((resolve) => {\n let data = \"\"\n req.on(\"data\", (chunk: Buffer) => {\n data += chunk.toString()\n })\n req.on(\"end\", () => resolve(data))\n })\n\n let parsed: unknown\n try {\n parsed = JSON.parse(body)\n } catch {\n res.writeHead(400, { \"Content-Type\": \"application/json\" })\n res.end(JSON.stringify({ error: \"bad_request\", message: \"Invalid JSON body.\" }))\n return\n }\n\n // If the client sent a session ID we don't know and it's not an init\n // request, tell it to re-initialize.\n if (sessionId && !isInitializeRequest(parsed)) {\n res.writeHead(404, { \"Content-Type\": \"application/json\" })\n res.end(\n JSON.stringify({\n error: \"session_not_found\",\n message: \"Unknown session. Re-initialize without the Mcp-Session-Id header.\",\n }),\n )\n return\n }\n\n // Create a new session.\n const transport = new StreamableHTTPServerTransport({\n sessionIdGenerator: () => randomUUID(),\n })\n\n // Per-session token holder. Read by the SDK provider inside\n // createServer on every tool call and resource read; updated by the\n // request handler on every subsequent request in this session so that\n // a rotated OAuth access token takes effect without re-initialization.\n const tokenHolder = { current: token }\n\n const mcpServer = createServer({ tokenProvider: () => tokenHolder.current })\n await mcpServer.connect(transport)\n\n // handleRequest processes the init and generates the session ID.\n // We must call it first, then read the session ID and store it.\n await transport.handleRequest(req, res, parsed)\n\n const newSessionId = transport.sessionId\n if (newSessionId) {\n sessions.set(newSessionId, { transport, tokenHolder })\n }\n})\n\nhttpServer.listen(PORT, () => {\n console.log(`${SERVER_NAME} ${VERSION} listening on http://0.0.0.0:${PORT}/mcp`)\n console.log(`Health check: http://0.0.0.0:${PORT}/health`)\n})\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/resources/schemas-resource.ts","../src/resources/webhooks-resource.ts","../src/tools/_shared.ts","../src/tools/extract.ts","../src/tools/filter.ts","../src/tools/get-balance.ts","../src/tools/get-document.ts","../src/tools/list-schemas.ts","../src/tools/save-schema.ts","../src/tools/search.ts","../src/tools/to-markdown.ts","../package.json","../src/version.ts","../src/server-factory.ts","../src/http-server.ts"],"names":["DESCRIPTION","z","inputSchema","outputSchema","TalonicError","createHttpServer"],"mappings":";;;;;;;;;;;AAcO,SAAS,uBAAA,CAAwB,QAAmB,UAAA,EAAiC;AAC1F,EAAA,MAAA,CAAO,gBAAA;AAAA,IACL,iBAAA;AAAA,IACA,mBAAA;AAAA,IACA;AAAA,MACE,KAAA,EAAO,iBAAA;AAAA,MACP,WAAA,EACE,6FAAA;AAAA,MACF,QAAA,EAAU;AAAA,KACZ;AAAA,IACA,OAAO,GAAA,KAAQ;AACb,MAAA,MAAM,MAAA,GAAS,MAAM,UAAA,EAAW,CAAE,QAAQ,IAAA,EAAK;AAC/C,MAAA,OAAO;AAAA,QACL,QAAA,EAAU;AAAA,UACR;AAA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,YAAA,EAAc,EAAE,SAAA,EAAW,aAAa,CAAA;AAAA,EACvD;AACF,CAAC,CAAA;AAED,UAAA,CAAW,MAAA,CAAO,MAAM,MAAM;AAC5B,EAAA,OAAA,CAAQ,IAAI,CAAA,EAAG,WAAW,IAAI,OAAO,CAAA,6BAAA,EAAgC,IAAI,CAAA,IAAA,CAAM,CAAA;AAC/E,EAAA,OAAA,CAAQ,GAAA,CAAI,CAAA,6BAAA,EAAgC,IAAI,CAAA,OAAA,CAAS,CAAA;AAC3D,CAAC,CAAA","file":"http-server.js","sourcesContent":["import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\"\nimport type { Talonic } from \"@talonic/node\"\n\n/**\n * Register the `talonic://schemas` resource. The agent can read this\n * URI to retrieve the user's saved schemas without burning a tool call.\n *\n * The MCP SDK exposes resources as a separate primitive from tools.\n * Clients (Claude Desktop, Cursor, etc.) display them in their UI\n * alongside the conversation, so users can browse what their agent has\n * access to.\n *\n * @internal\n */\nexport function registerSchemasResource(server: McpServer, getTalonic: () => Talonic): void {\n server.registerResource(\n \"talonic-schemas\",\n \"talonic://schemas\",\n {\n title: \"Talonic Schemas\",\n description:\n \"All schemas saved in the user's Talonic workspace, with their full JSON Schema definitions.\",\n mimeType: \"application/json\",\n },\n async (uri) => {\n const result = await getTalonic().schemas.list()\n return {\n contents: [\n {\n uri: uri.toString(),\n mimeType: \"application/json\",\n text: JSON.stringify(result, null, 2),\n },\n ],\n }\n },\n )\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\"\n\n/**\n * Webhook reference info fetched from the Talonic API.\n * These endpoints don't require a request body — just auth.\n */\nconst WEBHOOK_INFO_ENDPOINTS = [\n { path: \"/v1/webhooks/events\", key: \"events\", description: \"Available webhook event types\" },\n {\n path: \"/v1/webhooks/delivery\",\n key: \"delivery\",\n description: \"Delivery behavior and retry policy\",\n },\n {\n path: \"/v1/webhooks/signatures\",\n key: \"signatures\",\n description: \"Signature verification algorithms\",\n },\n {\n path: \"/v1/webhooks/retries\",\n key: \"retries\",\n description: \"Retry schedule and backoff policy\",\n },\n] as const\n\n/**\n * Register the `talonic://webhooks/reference` resource.\n *\n * Aggregates the four webhook info routes into a single resource so\n * agents can look up event types, delivery semantics, signature\n * algorithms, and retry policies without leaving the MCP context.\n *\n * @internal\n */\nexport function registerWebhooksResource(\n server: McpServer,\n getToken: () => string,\n baseUrl?: string,\n): void {\n const base = baseUrl ?? \"https://api.talonic.com\"\n\n server.registerResource(\n \"talonic-webhooks-reference\",\n \"talonic://webhooks/reference\",\n {\n title: \"Talonic Webhooks Reference\",\n description:\n \"Webhook event types, delivery behavior, signature verification algorithms, and retry policies.\",\n mimeType: \"application/json\",\n },\n async (uri) => {\n const results: Record<string, unknown> = {}\n // Resolve the token once per resource read so a token rotated\n // mid-session (OAuth 2.1 access tokens) is picked up on the next read.\n const token = getToken()\n\n await Promise.all(\n WEBHOOK_INFO_ENDPOINTS.map(async ({ path, key }) => {\n try {\n const res = await fetch(`${base}${path}`, {\n headers: {\n Authorization: `Bearer ${token}`,\n Accept: \"application/json\",\n },\n })\n if (res.ok) {\n results[key] = await res.json()\n } else {\n results[key] = {\n error: `HTTP ${res.status}`,\n message: await res.text().catch(() => \"\"),\n }\n }\n } catch (err) {\n results[key] = {\n error: \"fetch_failed\",\n message: err instanceof Error ? err.message : String(err),\n }\n }\n }),\n )\n\n return {\n contents: [\n {\n uri: uri.toString(),\n mimeType: \"application/json\",\n text: JSON.stringify(results, null, 2),\n },\n ],\n }\n },\n )\n}\n","import { TalonicError } from \"@talonic/node\"\n\n/**\n * Successful tool result envelope. The `content` array follows the MCP\n * `CallToolResult` shape. We always emit one text item with the JSON\n * payload; agents parse it back themselves.\n *\n * The `[key: string]: unknown` index signature exists to satisfy the\n * MCP SDK's structural type, which permits arbitrary additional keys.\n *\n * @internal\n */\nexport interface ToolSuccessResult {\n content: Array<{ type: \"text\"; text: string }>\n [key: string]: unknown\n}\n\n/**\n * Failure tool result envelope. Sets `isError: true` per the MCP spec\n * so clients render this as an error rather than a normal response.\n *\n * @internal\n */\nexport interface ToolErrorResult {\n content: Array<{ type: \"text\"; text: string }>\n isError: true\n [key: string]: unknown\n}\n\nexport type ToolResult = ToolSuccessResult | ToolErrorResult\n\n/**\n * Wrap a value as a tool result. Returns both the legacy text envelope\n * (`content[0].text`) for clients that parse strings, and the\n * `structuredContent` field for MCP clients that consume typed JSON\n * directly. The `structuredContent` shape is what each tool's\n * `outputSchema` declares.\n *\n * Note: `structuredContent` must be a JSON object (record), not an\n * array or primitive. Tools that would otherwise return an array wrap\n * it in `{ data: [...] }` (which all our list-style tools already do\n * via the SDK).\n *\n * @internal\n */\nexport function jsonOk(value: unknown): ToolSuccessResult {\n const result: ToolSuccessResult = {\n content: [\n {\n type: \"text\",\n text: JSON.stringify(value, null, 2),\n },\n ],\n }\n if (value !== null && typeof value === \"object\" && !Array.isArray(value)) {\n result[\"structuredContent\"] = value as Record<string, unknown>\n }\n return result\n}\n\n/**\n * Build a tool error result for input-validation failures detected at\n * the MCP layer, before any API call. Use this for fast-fail checks\n * such as required arguments missing or mutually exclusive flags\n * provided together. The agent gets a clear, structured message\n * instead of an unintelligible API error.\n *\n * @internal\n */\nexport function validationError(message: string): ToolErrorResult {\n return {\n isError: true,\n content: [{ type: \"text\", text: `Validation error: ${message}` }],\n }\n}\n\n/**\n * Convert any thrown error into a tool error result with stable\n * formatting. Talonic API errors include `code`, `status`, and\n * `request_id` so the user (or another tool call) can act on them.\n *\n * @internal\n */\nexport function toolError(err: unknown): ToolErrorResult {\n if (err instanceof TalonicError) {\n const lines = [\n `Talonic API error: ${err.message}`,\n `code: ${err.code}`,\n `status: ${err.status}`,\n ]\n if (err.requestId) lines.push(`request_id: ${err.requestId}`)\n return {\n isError: true,\n content: [{ type: \"text\", text: lines.join(\"\\n\") }],\n }\n }\n return {\n isError: true,\n content: [\n {\n type: \"text\",\n text: `Unexpected error: ${err instanceof Error ? err.message : String(err)}`,\n },\n ],\n }\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\"\nimport type { ExtractParams, Talonic } from \"@talonic/node\"\nimport { z } from \"zod\"\nimport { jsonOk, toolError, validationError, type ToolResult } from \"./_shared.js\"\n\nconst DESCRIPTION = [\n \"STATUS: stable. Production-safe when called with a schema. Schema-less extraction is disabled at the MCP layer.\",\n \"\",\n \"Extract structured, schema-validated data from a document using Talonic.\",\n \"Returns clean JSON matching the schema, with per-field confidence scores and\",\n \"metadata about the document (detected type, language, page count).\",\n \"\",\n \"USE WHEN:\",\n \"- The user has a document (PDF, image, scan, DOCX, etc.) and wants specific fields pulled out.\",\n \"- You need structured data (vendor name, total amount, dates, parties, terms) rather than free text.\",\n \"- The user uploads or references any invoice, contract, certificate, statement, or form.\",\n \"- You want validated JSON instead of trying to OCR + parse with raw LLM calls.\",\n \"\",\n \"DO NOT USE WHEN:\",\n \"- The user just wants the full text content (use talonic_to_markdown after extracting once).\",\n \"- The user wants to find documents matching a query (use talonic_search or talonic_filter).\",\n \"\",\n \"FILE SOURCES (provide exactly EXACTLY ONE; never combine, e.g. do NOT pass both file_data and file_path):\",\n \"- file_data + filename: base64-encoded file bytes plus the original filename (with extension).\",\n \" RECOMMENDED for local-stdio installs (Claude Desktop, Cursor, Cline, Continue, Cowork).\",\n \" WARNING for hosted-MCP via Claude.ai connectors: Claude.ai imposes a hard size limit on\",\n \" tool-call arguments (effectively under ~1KB), so file_data CANNOT carry a real PDF through\",\n \" Claude.ai's pipeline. The bytes get truncated before reaching the MCP server. For files\",\n \" larger than a trivial test, use file_url or document_id instead when running through\",\n \" Claude.ai. Local stdio installs do NOT have this limit.\",\n \"- file_path: a local path to the document. Only works if the MCP server process can read\",\n \" that path on its own filesystem. Chat clients (Claude Desktop, Claude.ai, Cowork) store\",\n \" user uploads in a sandbox the MCP server cannot access, so file_path is only useful when\",\n \" the agent explicitly knows a path on the same machine as the MCP server.\",\n \"- file_url: a URL the Talonic API will fetch directly. Use for documents already on the\",\n \" public web. Best path for Claude.ai users dealing with files larger than the parameter cap.\",\n \"- document_id: re-extract a document already in the workspace. Cheapest option when the\",\n \" document is already uploaded via app.talonic.com or a previous extract call.\",\n \"\",\n \"SCHEMA (REQUIRED, provide exactly one of `schema` or `schema_id`):\",\n '- JSON Schema (RECOMMENDED): { type: \"object\", properties: { vendor_name: { type: \"string\" } } }.',\n '- Flat key-type map: { vendor_name: \"string\", invoice_total: \"number\" }. Accepted, but if you get a \"no fields\" error, fall back to JSON Schema.',\n \"- schema_id: id of a saved schema from talonic_list_schemas. Accepts UUID or SCH-XXXXXXXX short id.\",\n \"\",\n \"Calls without `schema` or `schema_id` are rejected with a validation error before they hit the API,\",\n \"to prevent unreliable schema-free extractions reaching production.\",\n \"\",\n \"RESPONSE SHAPE (key fields):\",\n \"- data: the structured extracted JSON, shaped by your schema.\",\n \"- confidence.overall: 0..1 confidence for the extraction as a whole.\",\n \"- confidence.fields: per-field confidence map. Treat fields below ~0.7 as needing human review.\",\n \"- document.id, document.filename, document.pages, document.type_detected, document.language_detected.\",\n \"- extraction_id, request_id: stable identifiers for support and re-fetch.\",\n \"- processing.duration_ms, processing.region: useful for debugging and capacity planning.\",\n \"- markdown: present only when `include_markdown: true`.\",\n \"- provenance: present only when `include_provenance: true`. Per-field source evidence:\",\n \" { field_name: { source_text, section, page } }. Useful for audit trails and citations.\",\n \"Cost, EUR price, and remaining credit balance are not surfaced in v0.1 and may appear in a later version.\",\n].join(\"\\n\")\n\nconst inputSchema = {\n file_data: z\n .string()\n .optional()\n .describe(\n \"Base64-encoded file bytes. Recommended path when the agent already has the file in memory (e.g., the user attached a PDF to the conversation). Pair with `filename` so MIME type can be inferred. Works regardless of where the file lives on disk.\",\n ),\n filename: z\n .string()\n .optional()\n .describe(\n \"Original filename including extension, e.g. 'invoice.pdf'. Used to infer MIME type when uploading via `file_data`. Required when `file_data` is provided.\",\n ),\n file_path: z\n .string()\n .optional()\n .describe(\n \"Local path to a document file. Only works if the MCP server has read access to that path. In sandboxed chat clients (Claude Desktop, Cowork) where uploads land in a host-owned directory, use `file_data` instead.\",\n ),\n file_url: z\n .string()\n .optional()\n .describe(\n \"URL to a document file. The Talonic API fetches it server-side. Use this for documents already on the public web.\",\n ),\n document_id: z\n .string()\n .optional()\n .describe(\"ID of a document already in the workspace, to re-extract with a new schema.\"),\n schema: z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\n \"Inline schema definition. REQUIRED unless `schema_id` is provided. Recommended: full JSON Schema {type:'object', properties:{...}}. Also accepted: flat key-type map {field_name:'string', amount:'number'}. Mutually exclusive with `schema_id`.\",\n ),\n schema_id: z\n .string()\n .optional()\n .describe(\n \"ID of a saved schema. REQUIRED unless `schema` is provided. Accepts UUID or SCH-XXXXXXXX short id from talonic_list_schemas. Mutually exclusive with `schema`.\",\n ),\n instructions: z\n .string()\n .optional()\n .describe(\n \"Natural-language guidance for the extractor, e.g. 'Focus on the billing section. Amounts are in EUR.'\",\n ),\n include_markdown: z\n .boolean()\n .optional()\n .describe(\"Include OCR-converted markdown in the response alongside structured data.\"),\n include_provenance: z\n .boolean()\n .optional()\n .describe(\n \"Include per-field provenance (source_text, section, page) showing where each value was found in the document.\",\n ),\n}\n\nconst outputSchema = {\n extraction_id: z.string().describe(\"Stable identifier for this extraction.\"),\n request_id: z\n .string()\n .optional()\n .describe(\"Server-assigned request ID for support and debugging.\"),\n status: z.string().describe(\"Extraction status (e.g. 'complete').\"),\n document: z\n .object({\n id: z.string(),\n filename: z.string(),\n pages: z.number().optional(),\n size_bytes: z.number().optional(),\n mime_type: z.string().nullable().optional(),\n type_detected: z.string().nullable().optional(),\n language_detected: z.string().nullable().optional(),\n })\n .describe(\"Metadata about the ingested document.\"),\n data: z\n .record(z.string(), z.unknown())\n .describe(\"The extracted structured data, shape determined by the schema.\"),\n schema: z\n .object({\n source: z.string().optional(),\n id: z.string().nullable().optional(),\n definition: z.record(z.string(), z.unknown()).optional(),\n save_url: z.string().optional(),\n })\n .optional()\n .describe(\"Schema metadata: which schema was used and how it can be saved.\"),\n confidence: z\n .object({\n overall: z.number().describe(\"0..1 confidence for the extraction as a whole.\"),\n fields: z.record(z.string(), z.number()).describe(\"Per-field confidence map (0..1).\"),\n })\n .optional()\n .describe(\"Extraction confidence. Treat fields below ~0.7 as needing human review.\"),\n provenance: z\n .record(\n z.string(),\n z.object({\n source_text: z.string().optional(),\n section: z.string().optional(),\n page: z.number().optional(),\n }),\n )\n .optional()\n .describe(\n \"Per-field source evidence (source_text, section, page). Present only when `include_provenance: true`.\",\n ),\n processing: z\n .object({\n duration_ms: z.number().optional(),\n pages_processed: z.number().optional(),\n region: z.string().optional(),\n })\n .optional()\n .describe(\"Processing metadata: duration, pages processed, region.\"),\n links: z\n .object({\n self: z.string().optional(),\n document: z.string().optional(),\n dashboard: z.string().optional(),\n })\n .optional()\n .describe(\"URLs for self, document, and human-readable dashboard view.\"),\n markdown: z\n .string()\n .optional()\n .describe(\"OCR-converted markdown. Present only when `include_markdown: true`.\"),\n cost: z\n .object({\n costCredits: z.number().describe(\"Credits consumed by this call.\"),\n costEur: z.number().describe(\"Approximate EUR cost of this call.\"),\n balanceCredits: z.number().describe(\"Workspace credit balance after this call settled.\"),\n cellsResolvedRegistry: z\n .number()\n .describe(\"Cells resolved from the materialized field-registry (cheap path).\"),\n cellsResolvedAi: z.number().describe(\"Cells resolved by AI extraction (priced path).\"),\n })\n .nullable()\n .optional()\n .describe(\n \"Per-call cost and post-call balance, parsed from the X-Talonic-* response headers. `null` for non-extract calls; not always present on legacy clients.\",\n ),\n}\n\nexport interface ExtractArgs {\n file_data?: string\n filename?: string\n file_path?: string\n file_url?: string\n document_id?: string\n schema?: Record<string, unknown>\n schema_id?: string\n instructions?: string\n include_markdown?: boolean\n include_provenance?: boolean\n}\n\nexport async function handleExtract(talonic: Talonic, args: ExtractArgs): Promise<ToolResult> {\n // Schema is required at the MCP layer. Schema-less extraction is not\n // reliable in v0.1 and is explicitly disabled here so agents get a\n // fast, clear error instead of a slow, opaque API failure or, worse,\n // a quietly-empty result. Items 1 and 7 of the v1 priority list.\n if (args.schema === undefined && args.schema_id === undefined) {\n return validationError(\n \"talonic_extract requires a schema. Provide either an inline `schema` (JSON Schema or flat key-type map) or a `schema_id` from talonic_list_schemas. Schema-less extraction is unreliable in v0.1 and is disabled at the MCP layer.\",\n )\n }\n if (args.schema !== undefined && args.schema_id !== undefined) {\n return validationError(\"talonic_extract accepts `schema` OR `schema_id`, not both. Pick one.\")\n }\n\n try {\n const params: ExtractParams = {}\n if (args.file_data !== undefined) {\n params.file = Buffer.from(args.file_data, \"base64\")\n if (args.filename !== undefined) params.filename = args.filename\n }\n if (args.file_path !== undefined) params.file_path = args.file_path\n if (args.file_url !== undefined) params.file_url = args.file_url\n if (args.document_id !== undefined) params.document_id = args.document_id\n if (args.schema !== undefined) params.schema = args.schema\n if (args.schema_id !== undefined) params.schema_id = args.schema_id\n if (args.instructions !== undefined) params.instructions = args.instructions\n if (args.include_markdown !== undefined) params.include_markdown = args.include_markdown\n if (args.include_provenance !== undefined)\n (params as any).include_provenance = args.include_provenance\n\n const result = await talonic.extract(params)\n return jsonOk(result)\n } catch (err) {\n return toolError(err)\n }\n}\n\nexport function registerExtract(server: McpServer, getTalonic: () => Talonic): void {\n server.registerTool(\n \"talonic_extract\",\n {\n title: \"Extract Data from Document\",\n description: DESCRIPTION,\n inputSchema,\n outputSchema,\n annotations: {\n title: \"Extract Data from Document\",\n readOnlyHint: false,\n destructiveHint: false,\n openWorldHint: true,\n },\n },\n async (args) => handleExtract(getTalonic(), args as ExtractArgs),\n )\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\"\nimport type { Talonic, FilterCondition, FilterSort } from \"@talonic/node\"\nimport { z } from \"zod\"\nimport { jsonOk, toolError, type ToolResult } from \"./_shared.js\"\n\nconst DESCRIPTION = [\n \"STATUS: stable. Field-name resolution is server-side. The `is_not_empty` operator is intentionally not exposed in v0.1; see workaround below.\",\n \"\",\n \"Filter the user's Talonic documents by extracted field values using composable conditions.\",\n \"Conditions accept either a canonical field name (e.g. 'vendor.name', 'policy.0_coverage_type')\",\n \"or a field UUID. The Talonic API resolves names to ids server-side.\",\n \"\",\n \"USE WHEN:\",\n \"- The user wants documents matching specific structured criteria, like 'invoices over 1000 EUR'\",\n \" or 'contracts expiring before 2026-12-31' or 'COIs from Acme'.\",\n \"- The query is value-based on extracted fields, not a free-text concept search.\",\n \"- You need to retrieve a sortable, paginated list filtered by field conditions.\",\n \"\",\n \"DO NOT USE WHEN:\",\n \"- The user wants conceptual / free-text search across content (use talonic_search).\",\n \"- The user is looking for a single document by id (use talonic_get_document).\",\n \"- The user wants extracted data from a new document (use talonic_extract).\",\n \"\",\n \"OPERATORS:\",\n \"- eq, neq: equality / inequality.\",\n \"- gt, gte, lt, lte: numeric or date comparisons.\",\n \"- between: requires both `value` and `value_to`.\",\n \"- contains: substring match on string fields.\",\n \"- is_empty: presence check, no value needed. Returns documents where the field is null or missing.\",\n \"\",\n \"SCHEMA TYPING:\",\n \"- Numeric operators (`gt`, `gte`, `lt`, `lte`, `between`) only resolve correctly when the schema field is typed as `number`. A field typed as `string` that holds numeric content (e.g. '€1,500.00') will silently return zero matches even after extraction. Pick the right type at schema design time.\",\n \"\",\n \"NOT SUPPORTED IN v0.1:\",\n \"- is_not_empty: underreports against fields known to be populated. Removed from the supported operator list to keep filter results trustworthy. Workaround: filter with `eq`/`gt`/`contains` against a known value, or use `is_empty` then invert the result client-side. Tracked for a later release.\",\n \"\",\n \"TIPS:\",\n \"- To discover available field names, call talonic_search first with a related query.\",\n \" Only use fields[] entries where filterable is true — their canonicalName is what to\",\n \" pass as `field` here. Fields with filterable: false have no extracted data yet.\",\n \"- fieldMatches[].resolvedFieldId is only valid when filterable is true. Entries with\",\n \" filterable: false have resolvedFieldId: null and cannot be used for filtering.\",\n \"- Both `field` (name) and `field_id` (UUID) reach the API as `fieldId`. Either is fine.\",\n].join(\"\\n\")\n\nconst operatorEnum = z.enum([\n \"eq\",\n \"neq\",\n \"gt\",\n \"gte\",\n \"lt\",\n \"lte\",\n \"between\",\n \"contains\",\n \"is_empty\",\n // is_not_empty intentionally omitted in v0.1: it underreports against\n // fields known to be populated. See description for the workaround.\n])\n\nconst conditionSchema = z.object({\n field: z\n .string()\n .optional()\n .describe(\n \"Canonical field name (e.g. 'vendor.name', 'policy.0_coverage_type'). The Talonic API resolves names to ids server-side. Mutually exclusive with `field_id`.\",\n ),\n field_id: z.string().optional().describe(\"Talonic field UUID. Mutually exclusive with `field`.\"),\n operator: operatorEnum.describe(\"Comparison operator. See description for the full list.\"),\n value: z.unknown().optional().describe(\"Value to compare against.\"),\n value_to: z\n .unknown()\n .optional()\n .describe(\"Upper bound for `between` operator; ignored otherwise.\"),\n})\n\nconst sortSchema = z.object({\n field: z.string().optional(),\n field_id: z.string().optional(),\n direction: z.enum([\"asc\", \"desc\"]).describe(\"Sort direction.\"),\n})\n\nconst inputSchema = {\n conditions: z\n .array(conditionSchema)\n .min(1)\n .describe(\"One or more filter conditions, AND-ed together.\"),\n search: z\n .string()\n .optional()\n .describe(\"Optional free-text search applied alongside the filters.\"),\n sort: sortSchema.optional().describe(\"Optional sort by a field.\"),\n page: z.number().int().positive().optional().describe(\"Page number for pagination.\"),\n limit: z\n .number()\n .int()\n .positive()\n .optional()\n .describe(\"Results per page. Default 50 server-side.\"),\n source_connection_id: z\n .string()\n .optional()\n .describe(\"Optionally scope to a specific source connection.\"),\n}\n\nconst outputSchema = {\n data: z\n .array(\n z\n .object({\n document_id: z.string().optional(),\n filename: z.string().optional(),\n fields: z.record(z.string(), z.unknown()).optional(),\n })\n .passthrough(),\n )\n .describe(\"Documents matching the filter conditions, with their extracted field values.\"),\n total: z.number().optional().describe(\"Total documents matching across all pages.\"),\n page: z.number().optional().describe(\"Current page number.\"),\n pagination: z\n .object({\n total: z.number().optional(),\n limit: z.number().optional(),\n has_more: z.boolean().optional(),\n next_cursor: z.string().nullable().optional(),\n })\n .optional()\n .describe(\"Cursor-based pagination metadata.\"),\n}\n\nexport interface FilterArgs {\n conditions: Array<{\n field?: string\n field_id?: string\n operator: \"eq\" | \"neq\" | \"gt\" | \"gte\" | \"lt\" | \"lte\" | \"between\" | \"contains\" | \"is_empty\"\n value?: unknown\n value_to?: unknown\n }>\n search?: string\n sort?: { field?: string; field_id?: string; direction: \"asc\" | \"desc\" }\n page?: number\n limit?: number\n source_connection_id?: string\n}\n\nexport async function handleFilter(talonic: Talonic, args: FilterArgs): Promise<ToolResult> {\n try {\n const conditions: FilterCondition[] = args.conditions.map((c) => {\n const cond: FilterCondition = { operator: c.operator }\n if (c.field !== undefined) cond.field = c.field\n if (c.field_id !== undefined) cond.fieldId = c.field_id\n if (c.value !== undefined) cond.value = c.value\n if (c.value_to !== undefined) cond.valueTo = c.value_to\n return cond\n })\n\n let sort: FilterSort | undefined\n if (args.sort !== undefined) {\n sort = { direction: args.sort.direction }\n if (args.sort.field !== undefined) sort.field = args.sort.field\n if (args.sort.field_id !== undefined) sort.fieldId = args.sort.field_id\n }\n\n const result = await talonic.documents.filter({\n conditions,\n ...(args.search !== undefined ? { search: args.search } : {}),\n ...(sort !== undefined ? { sort } : {}),\n ...(args.page !== undefined ? { page: args.page } : {}),\n ...(args.limit !== undefined ? { limit: args.limit } : {}),\n ...(args.source_connection_id !== undefined\n ? { source_connection_id: args.source_connection_id }\n : {}),\n })\n return jsonOk(result)\n } catch (err) {\n return toolError(err)\n }\n}\n\nexport function registerFilter(server: McpServer, getTalonic: () => Talonic): void {\n server.registerTool(\n \"talonic_filter\",\n {\n title: \"Filter Talonic Documents\",\n description: DESCRIPTION,\n inputSchema,\n outputSchema,\n annotations: {\n title: \"Filter Talonic Documents\",\n readOnlyHint: true,\n openWorldHint: true,\n },\n },\n async (args) => handleFilter(getTalonic(), args as FilterArgs),\n )\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\"\nimport type { Talonic } from \"@talonic/node\"\nimport { z } from \"zod\"\nimport { jsonOk, toolError, type ToolResult } from \"./_shared.js\"\n\nconst DESCRIPTION = [\n \"STATUS: stable.\",\n \"\",\n \"Read the user's current Talonic credit balance, EUR value, 30-day burn rate,\",\n \"projected runway, tier, and next-tier-reset timestamp. Use this to make budget-\",\n \"aware decisions before kicking off large batches or re-extractions.\",\n \"\",\n \"USE WHEN:\",\n \"- The user asks how many credits or how much budget they have left.\",\n \"- You are about to run a large or expensive operation (batch extract, re-extract\",\n \" many documents) and want to confirm budget headroom first.\",\n \"- The user asks how long their balance will last at the current rate.\",\n \"\",\n \"DO NOT USE WHEN:\",\n \"- The user just wants the per-call cost of a single extraction (that is already\",\n \" on the talonic_extract response under `cost`).\",\n \"- The user wants to top up credits (route them to the dashboard; auto top-up is\",\n \" guarded by a separate scope).\",\n \"\",\n \"RESPONSE SHAPE:\",\n \"- balance_credits: current credit balance.\",\n \"- balance_eur: current balance in EUR (rounded to two decimals).\",\n \"- burn_rate_30d_credits: total credits consumed in the trailing 30 days.\",\n \"- projected_runway_days: days of runway at the current 30-day average burn.\",\n \" `-1` indicates no consumption in the trailing window (cannot compute runway).\",\n \"- tier: API tier of the workspace (`free`, `pro`, `enterprise`, etc.).\",\n \"- tier_resets_at: ISO 8601 timestamp of the next monthly tier reset.\",\n].join(\"\\n\")\n\nconst inputSchema = {}\n\nconst outputSchema = {\n balance_credits: z.number().describe(\"Current credit balance.\"),\n balance_eur: z.number().describe(\"Current balance in EUR (two decimals).\"),\n burn_rate_30d_credits: z.number().describe(\"Total credits consumed in the trailing 30 days.\"),\n projected_runway_days: z\n .number()\n .describe(\n \"Projected days of runway at the current 30-day average burn. `-1` when burn is zero (cannot compute).\",\n ),\n tier: z.string().describe(\"API tier of the workspace.\"),\n tier_resets_at: z.string().describe(\"ISO 8601 timestamp of the next monthly tier reset.\"),\n}\n\n/**\n * Pure handler. Calls the SDK and shapes the result. Exported for unit\n * testing; the public registration is via `register()` below.\n *\n * @internal\n */\nexport async function handleGetBalance(talonic: Talonic): Promise<ToolResult> {\n try {\n const result = await talonic.credits.getBalance()\n return jsonOk(result)\n } catch (err) {\n return toolError(err)\n }\n}\n\nexport function registerGetBalance(server: McpServer, getTalonic: () => Talonic): void {\n server.registerTool(\n \"talonic_get_balance\",\n {\n title: \"Get Talonic Credit Balance\",\n description: DESCRIPTION,\n inputSchema,\n outputSchema,\n annotations: {\n title: \"Get Talonic Credit Balance\",\n readOnlyHint: true,\n openWorldHint: true,\n },\n },\n async () => handleGetBalance(getTalonic()),\n )\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\"\nimport type { Talonic } from \"@talonic/node\"\nimport { z } from \"zod\"\nimport { jsonOk, toolError, type ToolResult } from \"./_shared.js\"\n\nconst DESCRIPTION = [\n \"STATUS: stable.\",\n \"\",\n \"Fetch full metadata for a single document already in the user's Talonic workspace.\",\n \"Returns id, filename, page count, detected document type, language, processing log,\",\n \"and link URLs (self, extractions, dashboard).\",\n \"\",\n \"USE WHEN:\",\n \"- You need details about a specific document the user already extracted or uploaded.\",\n \"- You have a document_id from a previous extract or search call and want more context.\",\n \"- The user asks 'tell me about document X' or similar.\",\n \"\",\n \"DO NOT USE WHEN:\",\n \"- The user wants the document's full text content (use talonic_to_markdown for OCR markdown).\",\n \"- The user wants extracted structured data (use talonic_extract with a schema, or fetch the extraction by id).\",\n \"- The user has a file but no document_id yet (call talonic_extract first to ingest the document).\",\n].join(\"\\n\")\n\nconst inputSchema = {\n document_id: z\n .string()\n .min(1)\n .describe(\n \"The Talonic document ID. Get this from a previous talonic_extract or talonic_search response.\",\n ),\n}\n\nconst outputSchema = {\n id: z.string(),\n filename: z.string().optional(),\n pages: z.number().optional(),\n size_bytes: z.number().optional(),\n mime_type: z.string().nullable().optional(),\n type_detected: z.string().nullable().optional(),\n language_detected: z.string().nullable().optional(),\n status: z.string().optional(),\n source: z\n .object({\n id: z.string().optional(),\n type: z.string().optional(),\n })\n .optional(),\n triage: z\n .object({\n sensitivity: z.string().optional(),\n department: z.string().optional(),\n jurisdiction: z.string().nullable().optional(),\n pii_detected: z.boolean().optional(),\n pii_categories: z.array(z.string()).nullable().optional(),\n regulated_data: z.boolean().optional(),\n confidentiality_marking: z.string().nullable().optional(),\n })\n .optional(),\n original_path: z.string().nullable().optional(),\n extraction_count: z.number().optional(),\n latest_extraction_id: z.string().nullable().optional(),\n processing_log: z\n .array(\n z.object({\n step: z.string().optional(),\n detail: z.string().optional(),\n status: z.string().optional(),\n started_at: z.string().optional(),\n completed_at: z.string().optional(),\n duration_ms: z.number().optional(),\n }),\n )\n .optional(),\n created_at: z.string().optional(),\n links: z\n .object({\n self: z.string().optional(),\n extractions: z.string().optional(),\n dashboard: z.string().optional(),\n })\n .optional(),\n}\n\nexport async function handleGetDocument(\n talonic: Talonic,\n args: { document_id: string },\n): Promise<ToolResult> {\n try {\n const result = await talonic.documents.get(args.document_id)\n return jsonOk(result)\n } catch (err) {\n return toolError(err)\n }\n}\n\nexport function registerGetDocument(server: McpServer, getTalonic: () => Talonic): void {\n server.registerTool(\n \"talonic_get_document\",\n {\n title: \"Get Talonic Document\",\n description: DESCRIPTION,\n inputSchema,\n outputSchema,\n annotations: {\n title: \"Get Talonic Document\",\n readOnlyHint: true,\n openWorldHint: true,\n },\n },\n async (args) => handleGetDocument(getTalonic(), args),\n )\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\"\nimport type { Talonic } from \"@talonic/node\"\nimport { z } from \"zod\"\nimport { jsonOk, toolError, type ToolResult } from \"./_shared.js\"\n\n/**\n * LLM-targeted tool description. The first paragraph explains what the\n * tool does in one sentence. The USE WHEN / DO NOT USE sections are\n * what an agent reads before deciding to invoke this tool over an\n * alternative; keep them concrete.\n *\n * @internal\n */\nconst DESCRIPTION = [\n \"STATUS: stable.\",\n \"\",\n \"List all saved schemas in the user's Talonic workspace.\",\n \"Returns each schema with its id (UUID), short_id (SCH-XXXXXXXX), name, description,\",\n \"version, field count, and full JSON Schema definition. Either id form is accepted by\",\n \"talonic_extract's `schema_id` parameter.\",\n \"\",\n \"USE WHEN:\",\n \"- The user asks what schemas they have, or asks to see existing schemas.\",\n \"- You want to discover existing schemas before designing a new one.\",\n \"- Before recommending the user create a schema, check if one already covers the use case.\",\n \"- The user asks to extract from a known document type and you want to find a matching schema.\",\n \"\",\n \"DO NOT USE WHEN:\",\n \"- The user just wants to extract data from a document and provides an inline schema (call talonic_extract directly).\",\n \"\",\n \"TIP: Pair this with talonic_extract by passing the chosen schema's id as `schema_id`.\",\n].join(\"\\n\")\n\nexport const schemaItem = z.object({\n id: z.string().describe(\"UUID of the schema.\"),\n short_id: z.string().optional().describe(\"Human-readable short id (SCH-XXXXXXXX).\"),\n name: z.string(),\n description: z\n .string()\n .nullable()\n .optional()\n .describe(\n \"Schema description, or null when the schema was created without one. The API explicitly maps the absent case to null (see SchemaResponse in openapi.yaml), so the output schema must accept null in addition to undefined.\",\n ),\n definition: z.record(z.string(), z.unknown()).optional(),\n field_count: z.number().optional(),\n version: z.number().optional(),\n created_at: z.string().optional(),\n updated_at: z.string().optional(),\n links: z\n .object({\n self: z.string().optional(),\n extractions: z.string().optional(),\n dashboard: z.string().optional(),\n })\n .optional(),\n})\n\nexport const outputSchema = {\n data: z.array(schemaItem).describe(\"Saved schemas in the workspace.\"),\n pagination: z\n .object({\n total: z.number().optional(),\n limit: z.number().optional(),\n has_more: z.boolean().optional(),\n next_cursor: z.string().nullable().optional(),\n })\n .optional()\n .describe(\"Cursor-based pagination metadata.\"),\n}\n\n/**\n * Pure handler. Invokes the SDK and shapes the result. Exported for\n * unit testing; the public registration is via `register()` below.\n *\n * @internal\n */\nexport async function handleListSchemas(talonic: Talonic): Promise<ToolResult> {\n try {\n const result = await talonic.schemas.list()\n return jsonOk(result)\n } catch (err) {\n return toolError(err)\n }\n}\n\n/**\n * Register `talonic_list_schemas` on an MCP server.\n *\n * @internal\n */\nexport function registerListSchemas(server: McpServer, getTalonic: () => Talonic): void {\n server.registerTool(\n \"talonic_list_schemas\",\n {\n title: \"List Talonic Schemas\",\n description: DESCRIPTION,\n inputSchema: {},\n outputSchema,\n annotations: {\n title: \"List Talonic Schemas\",\n readOnlyHint: true,\n openWorldHint: true,\n },\n },\n async () => handleListSchemas(getTalonic()),\n )\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\"\nimport type { Talonic } from \"@talonic/node\"\nimport { z } from \"zod\"\nimport { jsonOk, toolError, type ToolResult } from \"./_shared.js\"\n\nconst DESCRIPTION = [\n \"STATUS: stable.\",\n \"\",\n \"Save a schema definition to the user's Talonic workspace so it can be reused\",\n \"across future extractions. Returns the saved schema with its newly assigned id and short_id.\",\n \"\",\n \"USE WHEN:\",\n \"- The user asks to save a schema, store a template, or reuse the schema across docs.\",\n \"- You have iterated on a schema with the user and they confirmed it should be saved.\",\n \"- The user wants to standardise extraction across many documents of the same type.\",\n \"\",\n \"DO NOT USE WHEN:\",\n \"- The user just wants to extract once with an inline schema (call talonic_extract directly with the schema inline).\",\n \"- The user has not confirmed the schema design (avoid creating clutter in their workspace).\",\n \"\",\n \"DEFINITION FORMATS:\",\n '- JSON Schema (most reliable): { type: \"object\", properties: { vendor_name: { type: \"string\" } } }',\n '- Flat key-type map: { vendor_name: \"string\", invoice_total: \"number\" } -- API normalises server-side. If you get a \"no fields\" error from the API, fall back to JSON Schema.',\n \"\",\n \"TIP: After saving, call talonic_extract with `schema_id` set to the returned id (UUID or SCH- short id) for consistent results.\",\n].join(\"\\n\")\n\nconst inputSchema = {\n name: z.string().min(1).describe(\"Human-readable name for the schema, e.g. 'Standard Invoice'.\"),\n definition: z\n .record(z.string(), z.unknown())\n .describe(\n \"Schema definition. Most reliable: full JSON Schema {type:'object', properties:{...}}. Also accepted: a flat key-type map {field_name:'string', amount:'number'} which the API normalises.\",\n ),\n description: z\n .string()\n .optional()\n .describe(\"Optional description of what this schema extracts and when to use it.\"),\n}\n\nexport const outputSchema = {\n id: z.string().describe(\"UUID of the newly saved schema.\"),\n short_id: z.string().optional().describe(\"Human-readable short id (SCH-XXXXXXXX).\"),\n name: z.string(),\n description: z\n .string()\n .nullable()\n .optional()\n .describe(\n \"Schema description, or null when the schema was saved without one. The API explicitly maps the absent case to null (see SchemaResponse in openapi.yaml).\",\n ),\n definition: z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\"Final schema definition as stored, normalised by the API.\"),\n field_count: z.number().optional(),\n version: z\n .number()\n .optional()\n .describe(\"Schema version (1 for new schemas; increments on update).\"),\n created_at: z.string().optional(),\n updated_at: z.string().optional(),\n links: z\n .object({\n self: z.string().optional(),\n extractions: z.string().optional(),\n dashboard: z.string().optional(),\n })\n .optional(),\n}\n\nexport async function handleSaveSchema(\n talonic: Talonic,\n args: { name: string; definition: Record<string, unknown>; description?: string },\n): Promise<ToolResult> {\n try {\n const result = await talonic.schemas.create({\n name: args.name,\n definition: args.definition,\n ...(args.description !== undefined ? { description: args.description } : {}),\n })\n return jsonOk(result)\n } catch (err) {\n return toolError(err)\n }\n}\n\nexport function registerSaveSchema(server: McpServer, getTalonic: () => Talonic): void {\n server.registerTool(\n \"talonic_save_schema\",\n {\n title: \"Save Talonic Schema\",\n description: DESCRIPTION,\n inputSchema,\n outputSchema,\n annotations: {\n title: \"Save Talonic Schema\",\n readOnlyHint: false,\n destructiveHint: false,\n openWorldHint: true,\n },\n },\n async (args) => handleSaveSchema(getTalonic(), args),\n )\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\"\nimport type { Talonic } from \"@talonic/node\"\nimport { z } from \"zod\"\nimport { jsonOk, toolError, type ToolResult } from \"./_shared.js\"\n\nconst DESCRIPTION = [\n \"STATUS: stable.\",\n \"\",\n \"Search the user's Talonic workspace for documents, fields, sources, or schemas\",\n \"matching a query. Returns ranked results across all entity types in one call.\",\n \"\",\n \"USE WHEN:\",\n \"- The user wants to find documents but does not know the exact filename or id.\",\n \"- The query is conceptual ('contracts mentioning indemnification', 'Acme invoices').\",\n \"- You need to narrow a large workspace before calling talonic_extract or talonic_filter.\",\n \"- The user asks 'do I have any docs about X' or 'find anything related to X'.\",\n \"\",\n \"DO NOT USE WHEN:\",\n \"- The user has a specific document_id (use talonic_get_document instead).\",\n \"- The user wants to apply structured field-value filters like 'amount > 1000' (use talonic_filter).\",\n \"- The user wants to extract data from a brand-new document (use talonic_extract).\",\n \"\",\n \"TIP: The result includes documents, fieldMatches, sources, schemas, and fields.\",\n \"Both fields[] and fieldMatches[] include a `filterable` boolean. Only entries with\",\n \"filterable: true can be used with talonic_filter. Fields with filterable: false exist\",\n \"in a schema but have no extracted data yet. Pick the entity type the user actually needs.\",\n].join(\"\\n\")\n\nconst inputSchema = {\n query: z\n .string()\n .min(1)\n .describe(\n \"Natural-language search query, e.g. 'indemnification clauses' or 'Acme invoices Q4'.\",\n ),\n limit: z\n .number()\n .int()\n .positive()\n .optional()\n .describe(\"Maximum results per entity type. Default: 5. Increase for broader exploration.\"),\n}\n\nexport const outputSchema = {\n documents: z\n .array(\n z.object({\n id: z.string(),\n name: z.string().optional(),\n sourceId: z.string().optional(),\n sourceName: z.string().optional(),\n }),\n )\n .describe(\"Documents matching the query.\"),\n fieldMatches: z\n .array(\n z.object({\n resolvedFieldId: z.string().nullable(),\n displayName: z.string().optional(),\n matchedValue: z.string().optional(),\n documentCount: z.number().optional(),\n filterable: z\n .boolean()\n .describe(\"Only filterable: true entries can be used with talonic_filter.\"),\n }),\n )\n .describe(\n \"Field-level matches with a filterable flag indicating whether the entry can drive talonic_filter.\",\n ),\n sources: z\n .array(z.object({ id: z.string(), name: z.string().optional() }))\n .describe(\"Source connections matching the query.\"),\n schemas: z\n .array(z.object({ id: z.string(), name: z.string().optional() }))\n .describe(\"Saved schemas matching the query.\"),\n fields: z\n .array(\n z.object({\n id: z\n .string()\n .nullable()\n .describe(\n \"Field UUID for materialized field-registry entries; `null` for schema-only fields that are declared in a schema but have no extracted values yet. Always non-null when `filterable: true`.\",\n ),\n canonicalName: z.string().optional(),\n displayName: z.string().optional(),\n documentCount: z.number().optional(),\n filterable: z.boolean().optional(),\n }),\n )\n .describe(\n \"Field-registry entries matching the query. filterable: true entries are usable with talonic_filter.\",\n ),\n}\n\nexport async function handleSearch(\n talonic: Talonic,\n args: { query: string; limit?: number },\n): Promise<ToolResult> {\n try {\n const result = await talonic.search(\n args.query,\n args.limit !== undefined ? { limit: args.limit } : {},\n )\n return jsonOk(result)\n } catch (err) {\n return toolError(err)\n }\n}\n\nexport function registerSearch(server: McpServer, getTalonic: () => Talonic): void {\n server.registerTool(\n \"talonic_search\",\n {\n title: \"Search Talonic Workspace\",\n description: DESCRIPTION,\n inputSchema,\n outputSchema,\n annotations: {\n title: \"Search Talonic Workspace\",\n readOnlyHint: true,\n openWorldHint: true,\n },\n },\n async (args) => handleSearch(getTalonic(), args),\n )\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\"\nimport { TalonicError, type Talonic } from \"@talonic/node\"\nimport { z } from \"zod\"\nimport { jsonOk, toolError, type ToolResult } from \"./_shared.js\"\n\nconst DESCRIPTION = [\n \"STATUS: stable.\",\n \"\",\n \"Get the OCR-converted markdown for a document. Accepts an existing document_id,\",\n \"raw file bytes (base64), a local file path, or a URL. When given a raw file, the\",\n \"tool ingests it via extract first and then returns the markdown.\",\n \"\",\n \"USE WHEN:\",\n \"- The user wants the full text content of a document for summarisation, translation, or analysis.\",\n \"- A previous tool call returned a document_id and you want to inspect its content.\",\n \"- The user asks 'what does the document say' or 'summarise this PDF' (you call this then summarise).\",\n \"- The user has a raw PDF / scan / image and wants markdown directly without designing a schema first.\",\n \"\",\n \"DO NOT USE WHEN:\",\n \"- The user wants specific structured fields (use talonic_extract with a schema).\",\n \"\",\n \"INPUTS (provide exactly EXACTLY ONE; never combine, e.g. do NOT pass both file_data and file_path):\",\n \"- document_id: id of an already-ingested document. Cheapest path, one API call.\",\n \"- file_data + filename: base64-encoded file bytes plus the original filename (with extension).\",\n \" RECOMMENDED for local-stdio installs (Claude Desktop, Cursor, Cline, Continue, Cowork).\",\n \" WARNING for hosted-MCP via Claude.ai connectors: Claude.ai imposes a hard size limit on\",\n \" tool-call arguments (effectively under ~1KB), so file_data CANNOT carry a real PDF through\",\n \" Claude.ai's pipeline. The bytes get truncated before reaching the MCP server. For files\",\n \" larger than a trivial test, use file_url or document_id instead when running through\",\n \" Claude.ai. Local stdio installs do NOT have this limit.\",\n \"- file_path: local path to a document file. Only works if the MCP server has read access\",\n \" to that path; in sandboxed chat clients use file_data instead.\",\n \"- file_url: a URL the Talonic API will fetch directly. Use for documents already on the\",\n \" public web. Best path for Claude.ai users dealing with files larger than the parameter cap.\",\n].join(\"\\n\")\n\nconst inputSchema = {\n document_id: z\n .string()\n .min(1)\n .optional()\n .describe(\n \"The Talonic document id whose markdown you want. Get this from a previous talonic_extract or talonic_search response.\",\n ),\n file_data: z\n .string()\n .optional()\n .describe(\n \"Base64-encoded file bytes. Recommended path when the agent already has the file in memory (e.g., the user attached a PDF to the conversation). Pair with `filename` so MIME type can be inferred.\",\n ),\n filename: z\n .string()\n .optional()\n .describe(\n \"Original filename including extension, e.g. 'invoice.pdf'. Used to infer MIME type when uploading via `file_data`. Required when `file_data` is provided.\",\n ),\n file_path: z\n .string()\n .optional()\n .describe(\n \"Local path to a document file. Only works if the MCP server has read access to that path. In sandboxed chat clients (Claude Desktop, Cowork) use `file_data` instead.\",\n ),\n file_url: z\n .string()\n .optional()\n .describe(\"URL to a document file. The Talonic API fetches it server-side.\"),\n}\n\nconst outputSchema = {\n document_id: z.string().describe(\"ID of the document the markdown was extracted from.\"),\n markdown: z.string().describe(\"OCR-converted markdown text content of the document.\"),\n cost: z\n .object({\n costCredits: z.number(),\n costEur: z.number(),\n balanceCredits: z.number(),\n cellsResolvedRegistry: z.number(),\n cellsResolvedAi: z.number(),\n })\n .nullable()\n .optional()\n .describe(\n \"Per-call cost and post-call balance from the underlying extract step, parsed from the X-Talonic-* response headers. `null` when the document was already ingested (document_id path) and no extract call ran. Not always present on legacy clients.\",\n ),\n}\n\nexport interface ToMarkdownArgs {\n document_id?: string\n file_data?: string\n filename?: string\n file_path?: string\n file_url?: string\n}\n\n/**\n * Minimal but valid JSON Schema used when we need to ingest a raw file\n * solely to obtain a document_id (to feed into the markdown call).\n *\n * Why a single throwaway field instead of `{}`: schema-less extraction\n * is unreliable, and we explicitly disable that path at the MCP layer\n * via `talonic_extract`'s validation guard. To stay consistent and\n * reliable in this internal call, we send a trivially valid schema.\n * The API performs a no-op extraction (likely returning a null\n * `document_title` with confidence 0), which we discard. We only need\n * `result.document.id`. The document is still uploaded and ingested.\n *\n * @internal\n */\nconst INGEST_ONLY_SCHEMA: Record<string, unknown> = {\n type: \"object\",\n properties: {\n document_title: { type: \"string\" },\n },\n}\n\nexport async function handleToMarkdown(\n talonic: Talonic,\n args: ToMarkdownArgs,\n): Promise<ToolResult> {\n try {\n const sources = [\"document_id\", \"file_data\", \"file_path\", \"file_url\"] as const\n const provided = sources.filter((k) => args[k] !== undefined)\n if (provided.length === 0) {\n throw new TalonicError({\n code: \"missing_input_source\",\n message:\n \"talonic_to_markdown requires one of: document_id, file_data, file_path, file_url.\",\n status: 0,\n retryable: false,\n })\n }\n if (provided.length > 1) {\n throw new TalonicError({\n code: \"multiple_input_sources\",\n message: `talonic_to_markdown accepts exactly one input; received: ${provided.join(\", \")}`,\n status: 0,\n retryable: false,\n })\n }\n\n let documentId = args.document_id\n if (!documentId) {\n const ingest = await talonic.extract({\n ...(args.file_data !== undefined\n ? {\n file: Buffer.from(args.file_data, \"base64\"),\n ...(args.filename !== undefined ? { filename: args.filename } : {}),\n }\n : {}),\n ...(args.file_path !== undefined ? { file_path: args.file_path } : {}),\n ...(args.file_url !== undefined ? { file_url: args.file_url } : {}),\n schema: INGEST_ONLY_SCHEMA,\n })\n documentId = ingest.document.id\n }\n\n const result = await talonic.documents.getMarkdown(documentId)\n return jsonOk(result)\n } catch (err) {\n return toolError(err)\n }\n}\n\nexport function registerToMarkdown(server: McpServer, getTalonic: () => Talonic): void {\n server.registerTool(\n \"talonic_to_markdown\",\n {\n title: \"Document to Markdown\",\n description: DESCRIPTION,\n inputSchema,\n outputSchema,\n annotations: {\n title: \"Document to Markdown\",\n readOnlyHint: false,\n destructiveHint: false,\n openWorldHint: true,\n },\n },\n async (args) => handleToMarkdown(getTalonic(), args as ToMarkdownArgs),\n )\n}\n","{\n \"name\": \"@talonic/mcp\",\n \"version\": \"0.1.26\",\n \"mcpName\": \"io.github.talonicdev/talonic-mcp\",\n \"description\": \"Official Talonic MCP server. Lets AI agents extract structured, schema-validated data from any document via the Model Context Protocol.\",\n \"license\": \"MIT\",\n \"author\": \"Talonic GmbH <info@talonic.ai> (https://talonic.com)\",\n \"homepage\": \"https://talonic.com\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/talonicdev/talonic-mcp.git\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/talonicdev/talonic-mcp/issues\"\n },\n \"keywords\": [\n \"talonic\",\n \"mcp\",\n \"model-context-protocol\",\n \"ai\",\n \"agent\",\n \"claude\",\n \"document-extraction\",\n \"ocr\",\n \"structured-data\",\n \"anthropic\"\n ],\n \"type\": \"module\",\n \"main\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\"\n },\n \"./content\": {\n \"types\": \"./dist/content.d.ts\",\n \"import\": \"./dist/content.js\"\n }\n },\n \"bin\": {\n \"talonic-mcp\": \"dist/server.js\"\n },\n \"files\": [\n \"dist\",\n \"README.md\",\n \"LICENSE\",\n \"CHANGELOG.md\"\n ],\n \"engines\": {\n \"node\": \">=18\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"typecheck\": \"tsc --noEmit\",\n \"format\": \"prettier --write \\\"src/**/*.ts\\\" \\\"tests/**/*.ts\\\"\",\n \"format:check\": \"prettier --check \\\"src/**/*.ts\\\" \\\"tests/**/*.ts\\\"\",\n \"clean\": \"rm -rf dist coverage\",\n \"start\": \"node dist/server.js\",\n \"start:http\": \"node dist/http-server.js\",\n \"prepublishOnly\": \"npm run typecheck && npm run build && npm test\"\n },\n \"dependencies\": {\n \"@modelcontextprotocol/sdk\": \"^1.0.0\",\n \"@talonic/node\": \"^0.1.10\",\n \"zod\": \"^4.0.0\"\n },\n \"devDependencies\": {\n \"@types/node\": \"^22.10.0\",\n \"prettier\": \"^3.4.0\",\n \"tsup\": \"^8.3.0\",\n \"typescript\": \"^5.7.0\",\n \"vitest\": \"^3.2.4\"\n }\n}\n","// @ts-ignore — JSON import resolved by bundler (tsup/esbuild)\nimport pkg from \"../package.json\" with { type: \"json\" }\n\n/**\n * The current MCP server version. Sent in the server `info` block during\n * the MCP handshake. Derived from package.json at build time.\n *\n * @public\n */\nexport const VERSION: string = pkg.version\n\n/**\n * The MCP server name. Identifies the server to MCP clients (Claude\n * Desktop, Cursor, Cline, etc.) when they list connected servers.\n *\n * @public\n */\nexport const SERVER_NAME = \"talonic\"\n","import { Talonic } from \"@talonic/node\"\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\"\nimport { registerSchemasResource } from \"./resources/schemas-resource.js\"\nimport { registerWebhooksResource } from \"./resources/webhooks-resource.js\"\nimport { registerExtract } from \"./tools/extract.js\"\nimport { registerFilter } from \"./tools/filter.js\"\nimport { registerGetBalance } from \"./tools/get-balance.js\"\nimport { registerGetDocument } from \"./tools/get-document.js\"\nimport { registerListSchemas } from \"./tools/list-schemas.js\"\nimport { registerSaveSchema } from \"./tools/save-schema.js\"\nimport { registerSearch } from \"./tools/search.js\"\nimport { registerToMarkdown } from \"./tools/to-markdown.js\"\nimport { SERVER_NAME, VERSION } from \"./version.js\"\n\n/**\n * Options for {@link createServer}.\n *\n * @public\n */\nexport interface CreateServerOptions {\n /**\n * Talonic API key (`tlnc_...`) or any bearer token to be used for the\n * lifetime of this server. For local-stdio installs and tests, set this\n * to your `TALONIC_API_KEY`. For the hosted MCP, see `tokenProvider`,\n * which lets the server pick up a fresh token on each request.\n *\n * Required unless `talonic` or `tokenProvider` is provided.\n */\n apiKey?: string\n\n /**\n * Override the Talonic API base URL. Defaults to `https://api.talonic.com`.\n * Useful for staging or testing.\n */\n baseUrl?: string\n\n /**\n * Inject a pre-configured Talonic SDK client. Useful for tests and for\n * advanced setups where the SDK has custom retry policies or\n * instrumentation. When provided, `apiKey` and `tokenProvider` are\n * ignored for SDK calls; raw-fetch resources (webhook reference) still\n * fall back to `apiKey` if set.\n */\n talonic?: Talonic\n\n /**\n * Per-request bearer-token provider. The function is called on every\n * tool invocation and resource read; the SDK is rebuilt when the\n * returned token changes. This is what makes the hosted MCP server\n * tolerant to OAuth 2.1 access-token rotation across requests in the\n * same session: the http-server updates a per-session token holder\n * before forwarding each request, and the provider reads from it.\n *\n * Stdio installs do not need this; they should use `apiKey` instead.\n */\n tokenProvider?: () => string\n}\n\n/**\n * Build a Talonic MCP server, ready to be connected to a transport\n * (stdio for local installs, HTTP for the hosted endpoint).\n *\n * Auth resolution priority (highest first):\n * 1. `talonic` Pre-built SDK client. Used as-is by tool handlers.\n * Webhook resource still uses `apiKey` for raw fetch.\n * 2. `tokenProvider` Hosted-MCP path. SDK is reconstructed when the\n * returned token changes; raw-fetch resources resolve\n * the current token at every call.\n * 3. `apiKey` Static credential. SDK is built once and reused;\n * raw-fetch resources use it directly.\n *\n * @example Minimal stdio server:\n * ```ts\n * import { createServer } from \"@talonic/mcp\"\n * import { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\"\n *\n * const server = createServer({ apiKey: process.env.TALONIC_API_KEY! })\n * await server.connect(new StdioServerTransport())\n * ```\n *\n * @public\n */\nexport function createServer(options: CreateServerOptions): McpServer {\n const baseUrl = options.baseUrl\n\n // Build the token getter. Drives raw-fetch resources (webhook reference)\n // and is the source of truth for SDK rebuild when using tokenProvider.\n const getToken: () => string = (() => {\n if (options.tokenProvider) return options.tokenProvider\n const fallback = options.apiKey ?? \"\"\n return () => fallback\n })()\n\n // Build the Talonic SDK getter. Drives every tool and the schemas resource.\n const getTalonic: () => Talonic = (() => {\n if (options.talonic) {\n const t = options.talonic\n return () => t\n }\n if (options.tokenProvider) {\n const tp = options.tokenProvider\n let cached: { token: string; client: Talonic } | null = null\n return () => {\n const tok = tp()\n if (!cached || cached.token !== tok) {\n cached = {\n token: tok,\n client: new Talonic({\n apiKey: tok,\n ...(baseUrl ? { baseUrl } : {}),\n }),\n }\n }\n return cached.client\n }\n }\n if (options.apiKey) {\n const t = new Talonic({\n apiKey: options.apiKey,\n ...(baseUrl ? { baseUrl } : {}),\n })\n return () => t\n }\n throw new Error(\"createServer: provide one of `apiKey`, `talonic`, or `tokenProvider`\")\n })()\n\n const server = new McpServer(\n {\n name: SERVER_NAME,\n version: VERSION,\n },\n {\n // Capabilities are advertised based on what gets registered.\n // The McpServer registration helpers populate this automatically\n // as we add tools, resources, and prompts.\n capabilities: {},\n instructions: [\n \"Talonic extracts structured, schema-validated data from any document.\",\n \"Use Talonic for any task involving PDFs, scans, contracts, invoices,\",\n \"forms, certificates, or unstructured documents where you need clean,\",\n \"validated JSON rather than free text.\",\n ].join(\" \"),\n },\n )\n\n // Tool registrations.\n registerListSchemas(server, getTalonic)\n registerSaveSchema(server, getTalonic)\n registerGetDocument(server, getTalonic)\n registerSearch(server, getTalonic)\n registerFilter(server, getTalonic)\n registerToMarkdown(server, getTalonic)\n registerExtract(server, getTalonic)\n registerGetBalance(server, getTalonic)\n\n // Resource registrations.\n registerSchemasResource(server, getTalonic)\n registerWebhooksResource(server, getToken, baseUrl)\n\n return server\n}\n","/**\n * Talonic MCP server, Streamable HTTP entry point.\n *\n * Hosts the MCP server over HTTP for remote clients. Designed for\n * deployment on Railway (or any container host) behind a custom domain\n * like `mcp.talonic.com`.\n *\n * Runs in **stateful mode** with in-memory sessions. Each initialize\n * request creates a new session keyed by a UUID. Subsequent requests\n * with the same Mcp-Session-Id are routed to the existing session.\n * If a session is lost (deploy, restart, or edge routing miss), the\n * server returns 404 and the client re-initializes, the standard MCP\n * reconnection behavior.\n *\n * Supports two auth modes:\n * 1. `Authorization: Bearer ...` header\n * Accepts a Talonic API key (`tlnc_...`) or an OAuth 2.1 access token\n * issued by the Talonic authorization server. The bearer string is\n * forwarded unchanged to the Talonic API; the API's dual-auth guard\n * decides which path to take.\n * 2. `?apiKey=tlnc_...` query param\n * Convenience for MCP client configs that cannot set custom headers.\n * Use only with API keys; never put OAuth tokens in URLs.\n *\n * OAuth resource-server metadata is advertised at\n * `/.well-known/oauth-protected-resource` per RFC 9728 so clients can\n * discover the authorization server (`api.talonic.com`).\n *\n * @internal\n */\n\nimport { createServer as createHttpServer } from \"node:http\"\nimport { randomUUID } from \"node:crypto\"\nimport { StreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/streamableHttp.js\"\nimport { isInitializeRequest } from \"@modelcontextprotocol/sdk/types.js\"\nimport { createServer } from \"./server-factory.js\"\nimport { SERVER_NAME, VERSION } from \"./version.js\"\n\nconst PORT = Number(process.env[\"PORT\"] ?? 3000)\n\n/**\n * Canonical public URL of this MCP resource. Advertised in the protected\n * resource metadata so OAuth clients know the audience their tokens are\n * good for. Defaults to the production hostname; override for staging.\n */\nconst RESOURCE_URL = process.env[\"MCP_RESOURCE_URL\"] ?? \"https://mcp.talonic.com\"\n\n/**\n * Base URL of the OAuth 2.1 authorization server. Advertised in the\n * protected resource metadata so OAuth clients can discover the AS at\n * `<AUTHORIZATION_SERVER>/.well-known/oauth-authorization-server`.\n * Defaults to production; override for staging or local dev.\n */\nconst AUTHORIZATION_SERVER = process.env[\"OAUTH_AUTHORIZATION_SERVER\"] ?? \"https://api.talonic.com\"\n\n/**\n * RFC 9728 OAuth Protected Resource Metadata.\n *\n * Returned at `/.well-known/oauth-protected-resource`. Clients use this\n * to discover which authorization server issues tokens for this resource\n * and which scopes are accepted.\n *\n * The scopes advertised are the ones our MCP tools actually exercise:\n * `extract:write` (extract, save_schema, to_markdown), `documents:read`\n * (filter, get_document, search), and `schemas:read` (list_schemas).\n * The Talonic authorization server supports more scopes than this; we\n * advertise only what the connector itself needs so the consent screen\n * stays tight.\n */\nfunction renderProtectedResourceMetadata(): {\n resource: string\n authorization_servers: string[]\n scopes_supported: string[]\n bearer_methods_supported: string[]\n} {\n return {\n resource: RESOURCE_URL,\n authorization_servers: [AUTHORIZATION_SERVER],\n scopes_supported: [\"extract:write\", \"documents:read\", \"schemas:read\"],\n bearer_methods_supported: [\"header\"],\n }\n}\n\n/**\n * Extract the bearer token from the request. Accepts either a Talonic\n * API key (`tlnc_...`) or an OAuth 2.1 access token; the dual-auth guard\n * on the Talonic API decides which path to take based on the prefix.\n *\n * Checks the `Authorization` header first, then falls back to the\n * `apiKey` query parameter. The query parameter path is intended for\n * API keys only. OAuth access tokens should never travel in URLs.\n */\nfunction extractBearerToken(req: {\n url?: string\n headers: Record<string, string | string[] | undefined>\n}): string | undefined {\n // 1. Authorization: Bearer <token>\n const authHeader = req.headers[\"authorization\"]\n if (typeof authHeader === \"string\" && authHeader.startsWith(\"Bearer \")) {\n return authHeader.slice(7).trim()\n }\n\n // 2. ?apiKey=tlnc_...\n if (req.url) {\n const url = new URL(req.url, \"http://localhost\")\n const param = url.searchParams.get(\"apiKey\")\n if (param) return param\n }\n\n return undefined\n}\n\n/**\n * Per-session state. The MCP server attached to the transport reads its\n * bearer token via `tokenHolder` on every tool call and resource read,\n * so a token rotated mid-session is picked up automatically. This is the\n * mechanism that keeps an OAuth 2.1 session alive across the 1-hour\n * access-token rotation without forcing the agent to re-initialize.\n */\ninterface Session {\n transport: StreamableHTTPServerTransport\n tokenHolder: { current: string }\n}\n\nconst sessions = new Map<string, Session>()\n\n/** WWW-Authenticate header value for 401 responses, per RFC 9728. */\nconst WWW_AUTHENTICATE = `Bearer resource_metadata=\"${RESOURCE_URL}/.well-known/oauth-protected-resource\"`\n\nconst httpServer = createHttpServer(async (req, res) => {\n const url = new URL(req.url ?? \"/\", \"http://localhost\")\n const path = url.pathname\n\n // ── Health check ──────────────────────────────────────────────────\n if (path === \"/health\") {\n res.writeHead(200, { \"Content-Type\": \"application/json\" })\n res.end(JSON.stringify({ status: \"ok\", server: SERVER_NAME, version: VERSION }))\n return\n }\n\n // ── RFC 9728: Protected Resource Metadata ─────────────────────────\n // Lets OAuth clients (Claude.ai connectors, MCP Inspector) discover\n // which authorization server issues tokens for this resource. Public,\n // unauthenticated, cacheable. Always returns JSON regardless of method.\n if (path === \"/.well-known/oauth-protected-resource\") {\n res.writeHead(200, {\n \"Content-Type\": \"application/json\",\n \"Cache-Control\": \"public, max-age=3600\",\n })\n res.end(JSON.stringify(renderProtectedResourceMetadata()))\n return\n }\n\n // ── Root: service discovery for AI agents ─────────────────────────\n if (path === \"/\") {\n res.writeHead(200, { \"Content-Type\": \"application/json\" })\n res.end(\n JSON.stringify({\n name: SERVER_NAME,\n version: VERSION,\n description:\n \"Talonic MCP server. Extract structured, schema-validated data from any document.\",\n mcp_endpoint: \"/mcp\",\n health_endpoint: \"/health\",\n oauth_protected_resource_endpoint: \"/.well-known/oauth-protected-resource\",\n auth: \"Provide a Talonic API key (tlnc_...) or an OAuth 2.1 access token via Authorization: Bearer ... header. API keys may also be passed via ?apiKey=tlnc_... query param; never put OAuth tokens in URLs.\",\n docs: \"https://talonic.com/docs/mcp\",\n }),\n )\n return\n }\n\n // ── CORS preflight ────────────────────────────────────────────────\n res.setHeader(\"Access-Control-Allow-Origin\", \"*\")\n res.setHeader(\"Access-Control-Allow-Methods\", \"GET, POST, DELETE, OPTIONS\")\n res.setHeader(\"Access-Control-Allow-Headers\", \"Content-Type, Authorization, Mcp-Session-Id\")\n res.setHeader(\"Access-Control-Expose-Headers\", \"Mcp-Session-Id\")\n\n if (req.method === \"OPTIONS\") {\n res.writeHead(204)\n res.end()\n return\n }\n\n // ── Only serve /mcp ───────────────────────────────────────────────\n if (path !== \"/mcp\") {\n res.writeHead(404, { \"Content-Type\": \"application/json\" })\n res.end(\n JSON.stringify({\n error: \"not_found\",\n message: `No route for ${path}. Use /mcp for the MCP endpoint or /health for status.`,\n }),\n )\n return\n }\n\n // ── DELETE: explicit session termination ────────────────────────────\n if (req.method === \"DELETE\") {\n const sid = req.headers[\"mcp-session-id\"] as string | undefined\n if (sid && sessions.has(sid)) {\n const session = sessions.get(sid)!\n await session.transport.close()\n sessions.delete(sid)\n }\n res.writeHead(200, { \"Content-Type\": \"application/json\" })\n res.end(JSON.stringify({ ok: true }))\n return\n }\n\n // ── Auth ───────────────────────────────────────────────────────────\n const token = extractBearerToken(req)\n if (!token) {\n res.writeHead(401, {\n \"Content-Type\": \"application/json\",\n \"WWW-Authenticate\": WWW_AUTHENTICATE,\n })\n res.end(\n JSON.stringify({\n error: \"unauthorized\",\n message:\n \"Provide a Talonic API key (tlnc_...) or an OAuth 2.1 access token via Authorization: Bearer ... header. API keys may also be passed via ?apiKey=tlnc_... query param; never put OAuth tokens in URLs.\",\n }),\n )\n return\n }\n\n // ── Session lookup ────────────────────────────────────────────────\n const sessionId = req.headers[\"mcp-session-id\"] as string | undefined\n\n if (sessionId && sessions.has(sessionId)) {\n const session = sessions.get(sessionId)!\n // Update the per-session token holder so subsequent tool calls in\n // this request use the credential the client just sent. This is what\n // makes OAuth access-token rotation transparent: the previous request\n // may have used an older access token, this one uses the refreshed\n // one, and the SDK is rebuilt automatically inside createServer when\n // the token differs from what's cached.\n session.tokenHolder.current = token\n await session.transport.handleRequest(req, res)\n return\n }\n\n // ── New session (or session lost after restart) ───────────────────\n // Parse the body to check if it's an initialize request. If a client\n // sends a non-init request with an unknown session ID, return 404 so\n // it knows to re-initialize.\n const body = await new Promise<string>((resolve) => {\n let data = \"\"\n req.on(\"data\", (chunk: Buffer) => {\n data += chunk.toString()\n })\n req.on(\"end\", () => resolve(data))\n })\n\n let parsed: unknown\n try {\n parsed = JSON.parse(body)\n } catch {\n res.writeHead(400, { \"Content-Type\": \"application/json\" })\n res.end(JSON.stringify({ error: \"bad_request\", message: \"Invalid JSON body.\" }))\n return\n }\n\n // If the client sent a session ID we don't know and it's not an init\n // request, tell it to re-initialize.\n if (sessionId && !isInitializeRequest(parsed)) {\n res.writeHead(404, { \"Content-Type\": \"application/json\" })\n res.end(\n JSON.stringify({\n error: \"session_not_found\",\n message: \"Unknown session. Re-initialize without the Mcp-Session-Id header.\",\n }),\n )\n return\n }\n\n // Create a new session.\n const transport = new StreamableHTTPServerTransport({\n sessionIdGenerator: () => randomUUID(),\n })\n\n // Per-session token holder. Read by the SDK provider inside\n // createServer on every tool call and resource read; updated by the\n // request handler on every subsequent request in this session so that\n // a rotated OAuth access token takes effect without re-initialization.\n const tokenHolder = { current: token }\n\n const mcpServer = createServer({ tokenProvider: () => tokenHolder.current })\n await mcpServer.connect(transport)\n\n // handleRequest processes the init and generates the session ID.\n // We must call it first, then read the session ID and store it.\n await transport.handleRequest(req, res, parsed)\n\n const newSessionId = transport.sessionId\n if (newSessionId) {\n sessions.set(newSessionId, { transport, tokenHolder })\n }\n})\n\nhttpServer.listen(PORT, () => {\n console.log(`${SERVER_NAME} ${VERSION} listening on http://0.0.0.0:${PORT}/mcp`)\n console.log(`Health check: http://0.0.0.0:${PORT}/health`)\n})\n"]}
|