@talonic/mcp 0.1.6 → 0.1.8

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.
@@ -0,0 +1,637 @@
1
+ import { createServer as createServer$1 } from 'http';
2
+ import { randomUUID } from 'crypto';
3
+ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
4
+ import { Talonic, TalonicError } from '@talonic/node';
5
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
6
+ import { z } from 'zod';
7
+
8
+ // src/http-server.ts
9
+
10
+ // src/resources/schemas-resource.ts
11
+ function registerSchemasResource(server, talonic) {
12
+ server.registerResource(
13
+ "talonic-schemas",
14
+ "talonic://schemas",
15
+ {
16
+ title: "Talonic Schemas",
17
+ description: "All schemas saved in the user's Talonic workspace, with their full JSON Schema definitions.",
18
+ mimeType: "application/json"
19
+ },
20
+ async (uri) => {
21
+ const result = await talonic.schemas.list();
22
+ return {
23
+ contents: [
24
+ {
25
+ uri: uri.toString(),
26
+ mimeType: "application/json",
27
+ text: JSON.stringify(result, null, 2)
28
+ }
29
+ ]
30
+ };
31
+ }
32
+ );
33
+ }
34
+ function jsonOk(value) {
35
+ return {
36
+ content: [
37
+ {
38
+ type: "text",
39
+ text: JSON.stringify(value, null, 2)
40
+ }
41
+ ]
42
+ };
43
+ }
44
+ function toolError(err) {
45
+ if (err instanceof TalonicError) {
46
+ const lines = [
47
+ `Talonic API error: ${err.message}`,
48
+ `code: ${err.code}`,
49
+ `status: ${err.status}`
50
+ ];
51
+ if (err.requestId) lines.push(`request_id: ${err.requestId}`);
52
+ return {
53
+ isError: true,
54
+ content: [{ type: "text", text: lines.join("\n") }]
55
+ };
56
+ }
57
+ return {
58
+ isError: true,
59
+ content: [
60
+ {
61
+ type: "text",
62
+ text: `Unexpected error: ${err instanceof Error ? err.message : String(err)}`
63
+ }
64
+ ]
65
+ };
66
+ }
67
+
68
+ // src/tools/extract.ts
69
+ var DESCRIPTION = [
70
+ "Extract structured, schema-validated data from a document using Talonic.",
71
+ "Returns clean JSON matching the schema, with per-field confidence scores and",
72
+ "metadata about the document (detected type, language, page count).",
73
+ "",
74
+ "USE WHEN:",
75
+ "- The user has a document (PDF, image, scan, DOCX, etc.) and wants specific fields pulled out.",
76
+ "- You need structured data (vendor name, total amount, dates, parties, terms) rather than free text.",
77
+ "- The user uploads or references any invoice, contract, certificate, statement, or form.",
78
+ "- You want validated JSON instead of trying to OCR + parse with raw LLM calls.",
79
+ "",
80
+ "DO NOT USE WHEN:",
81
+ "- The user just wants the full text content (use talonic_to_markdown after extracting once).",
82
+ "- The user wants to find documents matching a query (use talonic_search or talonic_filter).",
83
+ "",
84
+ "FILE SOURCES (provide exactly one):",
85
+ "- file_data + filename (RECOMMENDED for chat clients): base64-encoded file bytes plus",
86
+ " the original filename (with extension). Use this whenever you already have the file",
87
+ " in memory, e.g. the user attached it to the conversation. Works in every MCP client",
88
+ " regardless of where the file lives on disk.",
89
+ "- file_path: a local path to the document. Only works if the MCP server process can",
90
+ " read that path on its own filesystem; many chat clients (Claude Desktop, Cowork)",
91
+ " store user uploads in a sandbox the MCP server cannot access, in which case use",
92
+ " file_data instead.",
93
+ "- file_url: a URL the Talonic API will fetch directly. Use for documents already on",
94
+ " the public web.",
95
+ "- document_id: re-extract a document already in the workspace.",
96
+ "",
97
+ "SCHEMA FORMATS (provide at most one of `schema` or `schema_id`):",
98
+ '- JSON Schema (most reliable): { type: "object", properties: { vendor_name: { type: "string" } } }',
99
+ '- Flat key-type map: { vendor_name: "string", invoice_total: "number" } -- API normalises server-side. If you get a "no fields" error, fall back to JSON Schema.',
100
+ "- schema_id: id of a saved schema from talonic_list_schemas. Accepts the UUID or the SCH-XXXXXXXX short id.",
101
+ "",
102
+ "IMPORTANT: production currently rejects requests with no schema. Always provide either",
103
+ "an inline `schema` or a `schema_id`."
104
+ ].join("\n");
105
+ var inputSchema = {
106
+ file_data: z.string().optional().describe(
107
+ "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."
108
+ ),
109
+ filename: z.string().optional().describe(
110
+ "Original filename including extension, e.g. 'invoice.pdf'. Used to infer MIME type when uploading via `file_data`. Required when `file_data` is provided."
111
+ ),
112
+ file_path: z.string().optional().describe(
113
+ "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."
114
+ ),
115
+ file_url: z.string().optional().describe(
116
+ "URL to a document file. The Talonic API fetches it server-side. Use this for documents already on the public web."
117
+ ),
118
+ document_id: z.string().optional().describe("ID of a document already in the workspace, to re-extract with a new schema."),
119
+ schema: z.record(z.string(), z.unknown()).optional().describe(
120
+ "Inline 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. Mutually exclusive with `schema_id`."
121
+ ),
122
+ schema_id: z.string().optional().describe(
123
+ "ID of a saved schema. Accepts UUID or SCH-XXXXXXXX short id. Mutually exclusive with `schema`."
124
+ ),
125
+ instructions: z.string().optional().describe(
126
+ "Natural-language guidance for the extractor, e.g. 'Focus on the billing section. Amounts are in EUR.'"
127
+ ),
128
+ include_markdown: z.boolean().optional().describe("Include OCR-converted markdown in the response alongside structured data.")
129
+ };
130
+ async function handleExtract(talonic, args) {
131
+ try {
132
+ const params = {};
133
+ if (args.file_data !== void 0) {
134
+ params.file = Buffer.from(args.file_data, "base64");
135
+ if (args.filename !== void 0) params.filename = args.filename;
136
+ }
137
+ if (args.file_path !== void 0) params.file_path = args.file_path;
138
+ if (args.file_url !== void 0) params.file_url = args.file_url;
139
+ if (args.document_id !== void 0) params.document_id = args.document_id;
140
+ if (args.schema !== void 0) params.schema = args.schema;
141
+ if (args.schema_id !== void 0) params.schema_id = args.schema_id;
142
+ if (args.instructions !== void 0) params.instructions = args.instructions;
143
+ if (args.include_markdown !== void 0) params.include_markdown = args.include_markdown;
144
+ const result = await talonic.extract(params);
145
+ return jsonOk(result);
146
+ } catch (err) {
147
+ return toolError(err);
148
+ }
149
+ }
150
+ function registerExtract(server, talonic) {
151
+ server.registerTool(
152
+ "talonic_extract",
153
+ {
154
+ title: "Extract Data from Document",
155
+ description: DESCRIPTION,
156
+ inputSchema
157
+ },
158
+ async (args) => handleExtract(talonic, args)
159
+ );
160
+ }
161
+ var DESCRIPTION2 = [
162
+ "Filter the user's Talonic documents by extracted field values using composable conditions.",
163
+ "Conditions accept either a canonical field name (e.g. 'vendor.name', 'policy.0_coverage_type')",
164
+ "or a field UUID. The Talonic API resolves names to ids server-side.",
165
+ "",
166
+ "USE WHEN:",
167
+ "- The user wants documents matching specific structured criteria, like 'invoices over 1000 EUR'",
168
+ " or 'contracts expiring before 2026-12-31' or 'COIs from Acme'.",
169
+ "- The query is value-based on extracted fields, not a free-text concept search.",
170
+ "- You need to retrieve a sortable, paginated list filtered by field conditions.",
171
+ "",
172
+ "DO NOT USE WHEN:",
173
+ "- The user wants conceptual / free-text search across content (use talonic_search).",
174
+ "- The user is looking for a single document by id (use talonic_get_document).",
175
+ "- The user wants extracted data from a new document (use talonic_extract).",
176
+ "",
177
+ "OPERATORS:",
178
+ "- eq, neq: equality / inequality",
179
+ "- gt, gte, lt, lte: numeric or date comparisons",
180
+ "- between: requires both `value` and `value_to`",
181
+ "- contains: substring match on string fields",
182
+ "- is_empty: presence check (no value needed)",
183
+ "- is_not_empty: presence check (no value needed). Note: currently underreports;",
184
+ " use `eq` / `gt` / `contains` etc. against a known value when possible.",
185
+ "",
186
+ "TIPS:",
187
+ "- To discover available field names, call talonic_search first with a related query.",
188
+ " fields[].canonicalName from the response is what to pass as `field` here.",
189
+ "- Both `field` (name) and `field_id` (UUID) reach the API as `fieldId`. Either is fine."
190
+ ].join("\n");
191
+ var operatorEnum = z.enum([
192
+ "eq",
193
+ "neq",
194
+ "gt",
195
+ "gte",
196
+ "lt",
197
+ "lte",
198
+ "between",
199
+ "contains",
200
+ "is_empty",
201
+ "is_not_empty"
202
+ ]);
203
+ var conditionSchema = z.object({
204
+ field: z.string().optional().describe(
205
+ "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`."
206
+ ),
207
+ field_id: z.string().optional().describe("Talonic field UUID. Mutually exclusive with `field`."),
208
+ operator: operatorEnum.describe("Comparison operator. See description for the full list."),
209
+ value: z.unknown().optional().describe("Value to compare against."),
210
+ value_to: z.unknown().optional().describe("Upper bound for `between` operator; ignored otherwise.")
211
+ });
212
+ var sortSchema = z.object({
213
+ field: z.string().optional(),
214
+ field_id: z.string().optional(),
215
+ direction: z.enum(["asc", "desc"]).describe("Sort direction.")
216
+ });
217
+ var inputSchema2 = {
218
+ conditions: z.array(conditionSchema).min(1).describe("One or more filter conditions, AND-ed together."),
219
+ search: z.string().optional().describe("Optional free-text search applied alongside the filters."),
220
+ sort: sortSchema.optional().describe("Optional sort by a field."),
221
+ page: z.number().int().positive().optional().describe("Page number for pagination."),
222
+ limit: z.number().int().positive().optional().describe("Results per page. Default 50 server-side."),
223
+ source_connection_id: z.string().optional().describe("Optionally scope to a specific source connection.")
224
+ };
225
+ async function handleFilter(talonic, args) {
226
+ try {
227
+ const conditions = args.conditions.map((c) => {
228
+ const cond = { operator: c.operator };
229
+ if (c.field !== void 0) cond.field = c.field;
230
+ if (c.field_id !== void 0) cond.fieldId = c.field_id;
231
+ if (c.value !== void 0) cond.value = c.value;
232
+ if (c.value_to !== void 0) cond.valueTo = c.value_to;
233
+ return cond;
234
+ });
235
+ let sort;
236
+ if (args.sort !== void 0) {
237
+ sort = { direction: args.sort.direction };
238
+ if (args.sort.field !== void 0) sort.field = args.sort.field;
239
+ if (args.sort.field_id !== void 0) sort.fieldId = args.sort.field_id;
240
+ }
241
+ const result = await talonic.documents.filter({
242
+ conditions,
243
+ ...args.search !== void 0 ? { search: args.search } : {},
244
+ ...sort !== void 0 ? { sort } : {},
245
+ ...args.page !== void 0 ? { page: args.page } : {},
246
+ ...args.limit !== void 0 ? { limit: args.limit } : {},
247
+ ...args.source_connection_id !== void 0 ? { source_connection_id: args.source_connection_id } : {}
248
+ });
249
+ return jsonOk(result);
250
+ } catch (err) {
251
+ return toolError(err);
252
+ }
253
+ }
254
+ function registerFilter(server, talonic) {
255
+ server.registerTool(
256
+ "talonic_filter",
257
+ {
258
+ title: "Filter Talonic Documents",
259
+ description: DESCRIPTION2,
260
+ inputSchema: inputSchema2
261
+ },
262
+ async (args) => handleFilter(talonic, args)
263
+ );
264
+ }
265
+ var DESCRIPTION3 = [
266
+ "Fetch full metadata for a single document already in the user's Talonic workspace.",
267
+ "Returns id, filename, page count, detected document type, language, processing log,",
268
+ "and link URLs (self, extractions, dashboard).",
269
+ "",
270
+ "USE WHEN:",
271
+ "- You need details about a specific document the user already extracted or uploaded.",
272
+ "- You have a document_id from a previous extract or search call and want more context.",
273
+ "- The user asks 'tell me about document X' or similar.",
274
+ "",
275
+ "DO NOT USE WHEN:",
276
+ "- The user wants the document's full text content (use talonic_to_markdown for OCR markdown).",
277
+ "- The user wants extracted structured data (use talonic_extract with a schema, or fetch the extraction by id).",
278
+ "- The user has a file but no document_id yet (call talonic_extract first to ingest the document)."
279
+ ].join("\n");
280
+ var inputSchema3 = {
281
+ document_id: z.string().min(1).describe(
282
+ "The Talonic document ID. Get this from a previous talonic_extract or talonic_search response."
283
+ )
284
+ };
285
+ async function handleGetDocument(talonic, args) {
286
+ try {
287
+ const result = await talonic.documents.get(args.document_id);
288
+ return jsonOk(result);
289
+ } catch (err) {
290
+ return toolError(err);
291
+ }
292
+ }
293
+ function registerGetDocument(server, talonic) {
294
+ server.registerTool(
295
+ "talonic_get_document",
296
+ {
297
+ title: "Get Talonic Document",
298
+ description: DESCRIPTION3,
299
+ inputSchema: inputSchema3
300
+ },
301
+ async (args) => handleGetDocument(talonic, args)
302
+ );
303
+ }
304
+
305
+ // src/tools/list-schemas.ts
306
+ var DESCRIPTION4 = [
307
+ "List all saved schemas in the user's Talonic workspace.",
308
+ "Returns each schema with its id, name, description, version,",
309
+ "field count, and full JSON Schema definition.",
310
+ "",
311
+ "USE WHEN:",
312
+ "- The user asks what schemas they have, or asks to see existing schemas.",
313
+ "- You want to discover existing schemas before designing a new one.",
314
+ "- Before recommending the user create a schema, check if one already covers the use case.",
315
+ "- The user asks to extract from a known document type and you want to find a matching schema.",
316
+ "",
317
+ "DO NOT USE WHEN:",
318
+ "- The user just wants to extract data from a document and provides an inline schema (call talonic_extract directly).",
319
+ "",
320
+ "TIP: Pair this with talonic_extract by passing the chosen schema's id as `schema_id`."
321
+ ].join("\n");
322
+ async function handleListSchemas(talonic) {
323
+ try {
324
+ const result = await talonic.schemas.list();
325
+ return jsonOk(result);
326
+ } catch (err) {
327
+ return toolError(err);
328
+ }
329
+ }
330
+ function registerListSchemas(server, talonic) {
331
+ server.registerTool(
332
+ "talonic_list_schemas",
333
+ {
334
+ title: "List Talonic Schemas",
335
+ description: DESCRIPTION4,
336
+ inputSchema: {}
337
+ },
338
+ async () => handleListSchemas(talonic)
339
+ );
340
+ }
341
+ var DESCRIPTION5 = [
342
+ "Save a schema definition to the user's Talonic workspace so it can be reused",
343
+ "across future extractions. Returns the saved schema with its newly assigned id and short_id.",
344
+ "",
345
+ "USE WHEN:",
346
+ "- The user asks to save a schema, store a template, or reuse the schema across docs.",
347
+ "- You have iterated on a schema with the user and they confirmed it should be saved.",
348
+ "- The user wants to standardise extraction across many documents of the same type.",
349
+ "",
350
+ "DO NOT USE WHEN:",
351
+ "- The user just wants to extract once with an inline schema (call talonic_extract directly with the schema inline).",
352
+ "- The user has not confirmed the schema design (avoid creating clutter in their workspace).",
353
+ "",
354
+ "DEFINITION FORMATS:",
355
+ '- JSON Schema (most reliable): { type: "object", properties: { vendor_name: { type: "string" } } }',
356
+ '- 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.',
357
+ "",
358
+ "TIP: After saving, call talonic_extract with `schema_id` set to the returned id (UUID or SCH- short id) for consistent results."
359
+ ].join("\n");
360
+ var inputSchema4 = {
361
+ name: z.string().min(1).describe("Human-readable name for the schema, e.g. 'Standard Invoice'."),
362
+ definition: z.record(z.string(), z.unknown()).describe(
363
+ "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."
364
+ ),
365
+ description: z.string().optional().describe("Optional description of what this schema extracts and when to use it.")
366
+ };
367
+ async function handleSaveSchema(talonic, args) {
368
+ try {
369
+ const result = await talonic.schemas.create({
370
+ name: args.name,
371
+ definition: args.definition,
372
+ ...args.description !== void 0 ? { description: args.description } : {}
373
+ });
374
+ return jsonOk(result);
375
+ } catch (err) {
376
+ return toolError(err);
377
+ }
378
+ }
379
+ function registerSaveSchema(server, talonic) {
380
+ server.registerTool(
381
+ "talonic_save_schema",
382
+ {
383
+ title: "Save Talonic Schema",
384
+ description: DESCRIPTION5,
385
+ inputSchema: inputSchema4
386
+ },
387
+ async (args) => handleSaveSchema(talonic, args)
388
+ );
389
+ }
390
+ var DESCRIPTION6 = [
391
+ "Search the user's Talonic workspace for documents, fields, sources, or schemas",
392
+ "matching a query. Returns ranked results across all entity types in one call.",
393
+ "",
394
+ "USE WHEN:",
395
+ "- The user wants to find documents but does not know the exact filename or id.",
396
+ "- The query is conceptual ('contracts mentioning indemnification', 'Acme invoices').",
397
+ "- You need to narrow a large workspace before calling talonic_extract or talonic_filter.",
398
+ "- The user asks 'do I have any docs about X' or 'find anything related to X'.",
399
+ "",
400
+ "DO NOT USE WHEN:",
401
+ "- The user has a specific document_id (use talonic_get_document instead).",
402
+ "- The user wants to apply structured field-value filters like 'amount > 1000' (use talonic_filter).",
403
+ "- The user wants to extract data from a brand-new document (use talonic_extract).",
404
+ "",
405
+ "TIP: The result includes documents, fieldMatches, sources, schemas, and fields. Pick the entity type the user actually needs."
406
+ ].join("\n");
407
+ var inputSchema5 = {
408
+ query: z.string().min(1).describe(
409
+ "Natural-language search query, e.g. 'indemnification clauses' or 'Acme invoices Q4'."
410
+ ),
411
+ limit: z.number().int().positive().optional().describe("Maximum results per entity type. Default: 5. Increase for broader exploration.")
412
+ };
413
+ async function handleSearch(talonic, args) {
414
+ try {
415
+ const result = await talonic.search(
416
+ args.query,
417
+ args.limit !== void 0 ? { limit: args.limit } : {}
418
+ );
419
+ return jsonOk(result);
420
+ } catch (err) {
421
+ return toolError(err);
422
+ }
423
+ }
424
+ function registerSearch(server, talonic) {
425
+ server.registerTool(
426
+ "talonic_search",
427
+ {
428
+ title: "Search Talonic Workspace",
429
+ description: DESCRIPTION6,
430
+ inputSchema: inputSchema5
431
+ },
432
+ async (args) => handleSearch(talonic, args)
433
+ );
434
+ }
435
+ var DESCRIPTION7 = [
436
+ "Get the OCR-converted markdown for a document. Accepts an existing document_id,",
437
+ "raw file bytes (base64), a local file path, or a URL. When given a raw file, the",
438
+ "tool ingests it via extract first and then returns the markdown.",
439
+ "",
440
+ "USE WHEN:",
441
+ "- The user wants the full text content of a document for summarisation, translation, or analysis.",
442
+ "- A previous tool call returned a document_id and you want to inspect its content.",
443
+ "- The user asks 'what does the document say' or 'summarise this PDF' (you call this then summarise).",
444
+ "- The user has a raw PDF / scan / image and wants markdown directly without designing a schema first.",
445
+ "",
446
+ "DO NOT USE WHEN:",
447
+ "- The user wants specific structured fields (use talonic_extract with a schema).",
448
+ "",
449
+ "INPUTS (provide exactly one):",
450
+ "- document_id: id of an already-ingested document (cheapest path; one API call)",
451
+ "- file_data + filename (RECOMMENDED for chat clients): base64-encoded file bytes plus",
452
+ " the original filename (with extension). Use this whenever you already have the file",
453
+ " in memory, e.g. the user attached it to the conversation. Works in every MCP client.",
454
+ "- file_path: local path to a document file. Only works if the MCP server has read access",
455
+ " to that path; in sandboxed chat clients use file_data instead.",
456
+ "- file_url: URL to a document file (the Talonic API fetches it server-side)"
457
+ ].join("\n");
458
+ var inputSchema6 = {
459
+ document_id: z.string().min(1).optional().describe(
460
+ "The Talonic document id whose markdown you want. Get this from a previous talonic_extract or talonic_search response."
461
+ ),
462
+ file_data: z.string().optional().describe(
463
+ "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."
464
+ ),
465
+ filename: z.string().optional().describe(
466
+ "Original filename including extension, e.g. 'invoice.pdf'. Used to infer MIME type when uploading via `file_data`. Required when `file_data` is provided."
467
+ ),
468
+ file_path: z.string().optional().describe(
469
+ "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."
470
+ ),
471
+ file_url: z.string().optional().describe("URL to a document file. The Talonic API fetches it server-side.")
472
+ };
473
+ var INGEST_ONLY_SCHEMA = {};
474
+ async function handleToMarkdown(talonic, args) {
475
+ try {
476
+ const sources = ["document_id", "file_data", "file_path", "file_url"];
477
+ const provided = sources.filter((k) => args[k] !== void 0);
478
+ if (provided.length === 0) {
479
+ throw new TalonicError({
480
+ code: "missing_input_source",
481
+ message: "talonic_to_markdown requires one of: document_id, file_data, file_path, file_url.",
482
+ status: 0,
483
+ retryable: false
484
+ });
485
+ }
486
+ if (provided.length > 1) {
487
+ throw new TalonicError({
488
+ code: "multiple_input_sources",
489
+ message: `talonic_to_markdown accepts exactly one input; received: ${provided.join(", ")}`,
490
+ status: 0,
491
+ retryable: false
492
+ });
493
+ }
494
+ let documentId = args.document_id;
495
+ if (!documentId) {
496
+ const ingest = await talonic.extract({
497
+ ...args.file_data !== void 0 ? {
498
+ file: Buffer.from(args.file_data, "base64"),
499
+ ...args.filename !== void 0 ? { filename: args.filename } : {}
500
+ } : {},
501
+ ...args.file_path !== void 0 ? { file_path: args.file_path } : {},
502
+ ...args.file_url !== void 0 ? { file_url: args.file_url } : {},
503
+ schema: INGEST_ONLY_SCHEMA
504
+ });
505
+ documentId = ingest.document.id;
506
+ }
507
+ const result = await talonic.documents.getMarkdown(documentId);
508
+ return jsonOk(result);
509
+ } catch (err) {
510
+ return toolError(err);
511
+ }
512
+ }
513
+ function registerToMarkdown(server, talonic) {
514
+ server.registerTool(
515
+ "talonic_to_markdown",
516
+ {
517
+ title: "Document to Markdown",
518
+ description: DESCRIPTION7,
519
+ inputSchema: inputSchema6
520
+ },
521
+ async (args) => handleToMarkdown(talonic, args)
522
+ );
523
+ }
524
+
525
+ // src/version.ts
526
+ var VERSION = "0.1.6";
527
+ var SERVER_NAME = "talonic";
528
+
529
+ // src/server-factory.ts
530
+ function createServer(options) {
531
+ const talonic = options.talonic ?? new Talonic({
532
+ apiKey: options.apiKey,
533
+ ...options.baseUrl ? { baseUrl: options.baseUrl } : {}
534
+ });
535
+ const server = new McpServer(
536
+ {
537
+ name: SERVER_NAME,
538
+ version: VERSION
539
+ },
540
+ {
541
+ // Capabilities are advertised based on what gets registered.
542
+ // The McpServer registration helpers populate this automatically
543
+ // as we add tools, resources, and prompts.
544
+ capabilities: {},
545
+ instructions: [
546
+ "Talonic extracts structured, schema-validated data from any document.",
547
+ "Use Talonic for any task involving PDFs, scans, contracts, invoices,",
548
+ "forms, certificates, or unstructured documents where you need clean,",
549
+ "validated JSON rather than free text."
550
+ ].join(" ")
551
+ }
552
+ );
553
+ registerListSchemas(server, talonic);
554
+ registerSaveSchema(server, talonic);
555
+ registerGetDocument(server, talonic);
556
+ registerSearch(server, talonic);
557
+ registerFilter(server, talonic);
558
+ registerToMarkdown(server, talonic);
559
+ registerExtract(server, talonic);
560
+ registerSchemasResource(server, talonic);
561
+ return server;
562
+ }
563
+
564
+ // src/http-server.ts
565
+ var PORT = Number(process.env["PORT"] ?? 3e3);
566
+ function extractApiKey(req) {
567
+ const authHeader = req.headers["authorization"];
568
+ if (typeof authHeader === "string" && authHeader.startsWith("Bearer ")) {
569
+ return authHeader.slice(7).trim();
570
+ }
571
+ if (req.url) {
572
+ const url = new URL(req.url, "http://localhost");
573
+ const param = url.searchParams.get("apiKey");
574
+ if (param) return param;
575
+ }
576
+ return void 0;
577
+ }
578
+ var sessions = /* @__PURE__ */ new Map();
579
+ var httpServer = createServer$1(async (req, res) => {
580
+ const url = new URL(req.url ?? "/", "http://localhost");
581
+ const path = url.pathname;
582
+ if (path === "/health") {
583
+ res.writeHead(200, { "Content-Type": "application/json" });
584
+ res.end(JSON.stringify({ status: "ok", server: SERVER_NAME, version: VERSION }));
585
+ return;
586
+ }
587
+ res.setHeader("Access-Control-Allow-Origin", "*");
588
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
589
+ res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Mcp-Session-Id");
590
+ res.setHeader("Access-Control-Expose-Headers", "Mcp-Session-Id");
591
+ if (req.method === "OPTIONS") {
592
+ res.writeHead(204);
593
+ res.end();
594
+ return;
595
+ }
596
+ if (path !== "/mcp") {
597
+ res.writeHead(404, { "Content-Type": "application/json" });
598
+ res.end(JSON.stringify({ error: "not_found", message: `No route for ${path}. Use /mcp for the MCP endpoint or /health for status.` }));
599
+ return;
600
+ }
601
+ const apiKey = extractApiKey(req);
602
+ if (!apiKey) {
603
+ res.writeHead(401, { "Content-Type": "application/json" });
604
+ res.end(JSON.stringify({ error: "unauthorized", message: "Provide a Talonic API key via Authorization: Bearer tlnc_... header or ?apiKey=tlnc_... query param." }));
605
+ return;
606
+ }
607
+ const sessionId = req.headers["mcp-session-id"];
608
+ if (sessionId && sessions.has(sessionId)) {
609
+ const session = sessions.get(sessionId);
610
+ await session.transport.handleRequest(req, res);
611
+ return;
612
+ }
613
+ if (sessionId && !sessions.has(sessionId)) {
614
+ res.writeHead(404, { "Content-Type": "application/json" });
615
+ res.end(JSON.stringify({ error: "session_not_found", message: "Unknown session. Start a new session without the Mcp-Session-Id header." }));
616
+ return;
617
+ }
618
+ const transport = new StreamableHTTPServerTransport({
619
+ sessionIdGenerator: () => randomUUID()
620
+ });
621
+ const mcpServer = createServer({ apiKey });
622
+ await mcpServer.connect(transport);
623
+ const newSessionId = transport.sessionId;
624
+ if (newSessionId) {
625
+ sessions.set(newSessionId, { transport });
626
+ transport.onclose = () => {
627
+ sessions.delete(newSessionId);
628
+ };
629
+ }
630
+ await transport.handleRequest(req, res);
631
+ });
632
+ httpServer.listen(PORT, () => {
633
+ console.log(`${SERVER_NAME} ${VERSION} listening on http://0.0.0.0:${PORT}/mcp`);
634
+ console.log(`Health check: http://0.0.0.0:${PORT}/health`);
635
+ });
636
+ //# sourceMappingURL=http-server.js.map
637
+ //# sourceMappingURL=http-server.js.map