@talonic/mcp 0.1.63 → 0.1.65

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.
@@ -613,6 +613,20 @@ var WIDGET_HTML9 = buildWidgetHtml({
613
613
  });
614
614
 
615
615
  // src/widgets/register.ts
616
+ function getWidgetTemplateHtml(uri) {
617
+ const map = {
618
+ [WIDGET_URIS.extract]: getExtractionResultWidgetHtml,
619
+ [WIDGET_URIS.search]: getSearchResultsWidgetHtml,
620
+ [WIDGET_URIS.filter]: getFilterResultsWidgetHtml,
621
+ [WIDGET_URIS.getDocument]: getDocumentMetaWidgetHtml,
622
+ [WIDGET_URIS.toMarkdown]: getMarkdownViewWidgetHtml,
623
+ [WIDGET_URIS.listSchemas]: getSchemaListWidgetHtml,
624
+ [WIDGET_URIS.saveSchema]: getSchemaSavedWidgetHtml,
625
+ [WIDGET_URIS.getBalance]: getBalanceWidgetHtml,
626
+ [WIDGET_URIS.requestUpload]: getUploadLinkWidgetHtml
627
+ };
628
+ return map[uri]?.();
629
+ }
616
630
  function registerExtractionResultWidget(server) {
617
631
  registerWidget(server, {
618
632
  name: "extraction-result-widget",
@@ -727,63 +741,13 @@ function toolError(err) {
727
741
 
728
742
  // src/tools/extract.ts
729
743
  var DESCRIPTION = [
730
- "STATUS: stable. Production-safe when called with a schema. Schema-less extraction is disabled at the MCP layer.",
731
- "",
732
- "Extract structured, schema-validated data from a document using Talonic.",
733
- "Returns clean JSON matching the schema, with per-field confidence scores and",
734
- "metadata about the document (detected type, language, page count).",
735
- "",
736
- "USE WHEN:",
737
- "- The user has a document (PDF, image, scan, DOCX, etc.) and wants specific fields pulled out.",
738
- "- You need structured data (vendor name, total amount, dates, parties, terms) rather than free text.",
739
- "- The user uploads or references any invoice, contract, certificate, statement, or form.",
740
- "- You want validated JSON instead of trying to OCR + parse with raw LLM calls.",
741
- "",
742
- "DO NOT USE WHEN:",
743
- "- The user just wants the full text content (use talonic_to_markdown after extracting once).",
744
- "- The user wants to find documents matching a query (use talonic_search or talonic_filter).",
745
- "",
746
- "FILE SOURCES (provide exactly EXACTLY ONE; never combine, e.g. do NOT pass both file_data and file_path):",
747
- "- file_data + filename: base64-encoded file bytes plus the original filename (with extension).",
748
- " RECOMMENDED for local-stdio installs (Claude Desktop, Cursor, Cline, Continue, Cowork).",
749
- " WARNING for hosted-MCP via Claude.ai connectors: Claude.ai imposes a hard size limit on",
750
- " tool-call arguments (effectively under ~1KB), so file_data CANNOT carry a real PDF through",
751
- " Claude.ai's pipeline. The bytes get truncated before reaching the MCP server. For files",
752
- " larger than a trivial test, use file_url or document_id instead when running through",
753
- " Claude.ai. Local stdio installs do NOT have this limit.",
754
- "- file_path: a local path to the document. Only works if the MCP server process can read",
755
- " that path on its own filesystem. Chat clients (Claude Desktop, Claude.ai, Cowork) store",
756
- " user uploads in a sandbox the MCP server cannot access, so file_path is only useful when",
757
- " the agent explicitly knows a path on the same machine as the MCP server.",
758
- "- file_url: a URL the Talonic API will fetch directly. Use for documents already on the",
759
- " public web. Best path for Claude.ai users dealing with files larger than the parameter cap.",
760
- "- document_id: re-extract a document already in the workspace. Cheapest option when the",
761
- " document is already uploaded via app.talonic.com or a previous extract call.",
744
+ "Extract structured, schema-validated JSON from a document. Returns the requested fields with per-field confidence scores.",
762
745
  "",
763
- "SCHEMA (REQUIRED, provide exactly one of `schema` or `schema_id`):",
764
- '- JSON Schema (RECOMMENDED): { type: "object", properties: { vendor_name: { type: "string" } } }.',
765
- '- Flat key-type map: { vendor_name: "string", invoice_total: "number" }. Accepted, but if you get a "no fields" error, fall back to JSON Schema.',
766
- "- schema_id: id of a saved schema from talonic_list_schemas. Accepts UUID or SCH-XXXXXXXX short id.",
767
- "",
768
- "Calls without `schema` or `schema_id` are rejected with a validation error before they hit the API,",
769
- "to prevent unreliable schema-free extractions reaching production.",
770
- "",
771
- "RESPONSE SHAPE (key fields):",
772
- "- data: the structured extracted JSON, shaped by your schema.",
773
- "- confidence.overall: 0..1 confidence for the extraction as a whole.",
774
- "- confidence.fields: per-field confidence map. Treat fields below ~0.7 as needing human review.",
775
- "- document.id, document.filename, document.pages, document.type_detected, document.language_detected.",
776
- "- extraction_id, request_id: stable identifiers for support and re-fetch.",
777
- "- processing.duration_ms, processing.region: useful for debugging and capacity planning.",
778
- "- markdown: present only when `include_markdown: true`.",
779
- "- provenance: present only when `include_provenance: true`. Per-field source evidence:",
780
- " { field_name: { source_text, section, page } }. Useful for audit trails and citations.",
781
- "Cost, EUR price, and remaining credit balance are not surfaced in v0.1 and may appear in a later version.",
782
- "",
783
- "LARGE FILES / HOSTED ENVIRONMENTS:",
784
- "For files larger than ~32KB, or when running in a hosted/sandboxed environment (Claude.ai, ChatGPT),",
785
- "use talonic_request_upload first to get a browser upload link, then use the returned document_id",
786
- "with this tool."
746
+ "USE WHEN: the user wants specific fields pulled from an invoice, contract, certificate, statement, form, scan, or PDF.",
747
+ "NOT FOR: full text (use talonic_to_markdown) \xB7 finding documents (use talonic_search / talonic_filter).",
748
+ "BY NAME: if the user names a file, call talonic_search first to get its document_id, then call this.",
749
+ "ARGS: a schema is REQUIRED \u2014 pass inline `schema` (JSON Schema, e.g. {type:'object',properties:{vendor_name:{type:'string'}}}) OR a saved `schema_id`, not both. Provide EXACTLY ONE document source: `document_id` (cheapest, a workspace doc), `file_url` (public URL), or `file_data`+`filename` (small local files only).",
750
+ "RETURNS: data (the JSON), confidence.overall and confidence.fields (treat <0.7 as needs review), document metadata, extraction_id."
787
751
  ].join("\n");
788
752
  var inputSchema = {
789
753
  file_data: z.string().optional().describe(
@@ -921,45 +885,13 @@ function registerExtract(server, getTalonic) {
921
885
  );
922
886
  }
923
887
  var DESCRIPTION2 = [
924
- "STATUS: stable. Field-name resolution is server-side.",
925
- "",
926
- "Filter the user's Talonic documents by extracted field values using composable conditions.",
927
- "Conditions accept either a canonical field name (e.g. 'vendor.name', 'policy.0_coverage_type')",
928
- "or a field UUID. The Talonic API resolves names to ids server-side.",
929
- "",
930
- "USE WHEN:",
931
- "- The user wants documents matching specific structured criteria, like 'invoices over 1000 EUR'",
932
- " or 'contracts expiring before 2026-12-31' or 'COIs from Acme'.",
933
- "- The query is value-based on extracted fields, not a free-text concept search.",
934
- "- You need to retrieve a sortable, paginated list filtered by field conditions.",
888
+ "Find documents by their extracted field VALUES using composable conditions (e.g. 'invoices where total > 1000').",
935
889
  "",
936
- "DO NOT USE WHEN:",
937
- "- The user wants conceptual / free-text search across content (use talonic_search).",
938
- "- The user is looking for a single document by id (use talonic_get_document).",
939
- "- The user wants extracted data from a new document (use talonic_extract).",
940
- "",
941
- "OPERATORS:",
942
- "- eq, neq: equality / inequality.",
943
- "- gt, gte, lt, lte: numeric or date comparisons.",
944
- "- between: requires both `value` and `value_to`.",
945
- "- contains: substring match on string fields.",
946
- "- is_empty: presence check, no value needed. Returns documents where the field is null or missing.",
947
- "- is_not_empty: presence check, no value needed. Returns documents where the field has a materialized value. Results reflect data within seconds of extraction completing.",
948
- "",
949
- "CONDITION SHAPE: each condition needs EXACTLY ONE of `field` or `field_id` (not both, not neither), an `operator`, and usually a `value`. Exceptions: `is_empty` / `is_not_empty` take NO value; `between` needs BOTH `value` (lower bound) and `value_to` (upper bound). `value`/`value_to` are a string, number, or boolean matching the field's data type (numbers for numeric fields, ISO 'YYYY-MM-DD' strings for dates).",
950
- "",
951
- "SCHEMA TYPING:",
952
- "- 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. '\u20AC1,500.00') will silently return zero matches even after extraction. Pick the right type at schema design time.",
953
- "- **Preventive check:** call `talonic_search` first and inspect `fieldMatches[].dataType` / `fields[].dataType` on the field you intend to filter. If `dataType !== 'number'`, do NOT use a numeric operator on it \u2014 either pick a different field, switch to a string-friendly operator (`eq`, `contains`), or warn the user that the schema field needs a `data_type` change before the filter can succeed.",
954
- "- **Reactive fallback:** if the filter response contains a `warnings` array, surface its `message` (and `suggestion`, if present) to the user verbatim \u2014 these explain *why* a query returned zero or unexpected results and typically suggest a schema-design change. Do not silently retry without flagging the warning.",
955
- "",
956
- "TIPS:",
957
- "- To discover available field names, call talonic_search first with a related query.",
958
- " Only use fields[] entries where filterable is true \u2014 their canonicalName is what to",
959
- " pass as `field` here. Fields with filterable: false have no extracted data yet.",
960
- "- fieldMatches[].resolvedFieldId is only valid when filterable is true. Entries with",
961
- " filterable: false have resolvedFieldId: null and cannot be used for filtering.",
962
- "- Both `field` (name) and `field_id` (UUID) reach the API as `fieldId`. Either is fine."
890
+ "USE WHEN: value-based criteria on extracted fields \u2014 numeric/date/text comparisons or presence checks.",
891
+ "NOT FOR: free-text / concept search (use talonic_search) \xB7 a single document by id (use talonic_get_document).",
892
+ "ARGS: conditions[] (AND-ed). Each = EXACTLY ONE of `field` (canonical name) or `field_id` (UUID), an `operator`, and usually a `value`. Operators: eq, neq, gt, gte, lt, lte, between (needs `value` AND `value_to`), contains, is_empty / is_not_empty (no value). `value`/`value_to` are string|number|boolean matching the field type (ISO YYYY-MM-DD for dates).",
893
+ "NUMERIC GUARD: gt/gte/lt/lte/between only work when the field's dataType is 'number'. Call talonic_search first and check dataType; a numeric op on a string field returns zero matches. If the response has `warnings[]`, surface them to the user \u2014 do not silently retry.",
894
+ "RETURNS: data[] (matching documents with field values), total, warnings[]."
963
895
  ].join("\n");
964
896
  var operatorEnum = z.enum([
965
897
  "eq",
@@ -1084,32 +1016,12 @@ function registerFilter(server, getTalonic) {
1084
1016
  );
1085
1017
  }
1086
1018
  var DESCRIPTION3 = [
1087
- "STATUS: stable.",
1088
- "",
1089
- "Read the user's current Talonic credit balance, EUR value, 30-day burn rate,",
1090
- "projected runway, tier, and next-tier-reset timestamp. Use this to make budget-",
1091
- "aware decisions before kicking off large batches or re-extractions.",
1019
+ "Read the workspace's Talonic credit balance, EUR value, tier, 30-day burn, and projected runway.",
1092
1020
  "",
1093
- "USE WHEN:",
1094
- "- The user asks how many credits or how much budget they have left.",
1095
- "- You are about to run a large or expensive operation (batch extract, re-extract",
1096
- " many documents) and want to confirm budget headroom first.",
1097
- "- The user asks how long their balance will last at the current rate.",
1098
- "",
1099
- "DO NOT USE WHEN:",
1100
- "- The user just wants the per-call cost of a single extraction (that is already",
1101
- " on the talonic_extract response under `cost`).",
1102
- "- The user wants to top up credits (route them to the dashboard; auto top-up is",
1103
- " guarded by a separate scope).",
1104
- "",
1105
- "RESPONSE SHAPE:",
1106
- "- balance_credits: current credit balance.",
1107
- "- balance_eur: current balance in EUR (rounded to two decimals).",
1108
- "- burn_rate_30d_credits: total credits consumed in the trailing 30 days.",
1109
- "- projected_runway_days: days of runway at the current 30-day average burn.",
1110
- " `-1` indicates no consumption in the trailing window (cannot compute runway).",
1111
- "- tier: API tier of the workspace (`free`, `pro`, `enterprise`, etc.).",
1112
- "- tier_resets_at: ISO 8601 timestamp of the next monthly tier reset."
1021
+ "USE WHEN: the user asks about credits/budget, or before a large batch when you want to confirm headroom.",
1022
+ "NOT FOR: the per-call cost of a single extraction (that is on the talonic_extract response).",
1023
+ "ARGS: none.",
1024
+ "RETURNS: balance_credits, balance_eur, tier, burn_rate_30d_credits, projected_runway_days (-1 = no recent usage), tier_resets_at."
1113
1025
  ].join("\n");
1114
1026
  var inputSchema3 = {};
1115
1027
  var outputSchema3 = {
@@ -1153,33 +1065,13 @@ function registerGetBalance(server, getTalonic) {
1153
1065
  );
1154
1066
  }
1155
1067
  var DESCRIPTION4 = [
1156
- "STATUS: stable.",
1157
- "",
1158
- "Fetch full metadata for a single document already in the user's Talonic workspace.",
1159
- "Returns id, filename, page count, detected document type, language, processing log,",
1160
- "and link URLs (self, extractions, dashboard).",
1161
- "",
1162
- "USE WHEN:",
1163
- "- You need details about a specific document the user already extracted or uploaded.",
1164
- "- You have a document_id from a previous extract or search call and want more context.",
1165
- "- You called talonic_request_upload and need to poll until the user has uploaded the file.",
1166
- "- The user asks 'tell me about document X' or similar.",
1167
- "",
1168
- "DO NOT USE WHEN:",
1169
- "- The user wants the document's full text content (use talonic_to_markdown for OCR markdown).",
1170
- "- The user wants extracted structured data (use talonic_extract with a schema, or fetch the extraction by id).",
1171
- "- The user has a file but no document_id yet (call talonic_extract first to ingest the document).",
1068
+ "Fetch a single document's metadata and processing status from the workspace.",
1172
1069
  "",
1173
- "STATUS VALUES on the response `status` field:",
1174
- "- pending_upload: document slot reserved via talonic_request_upload, file not yet received.",
1175
- " Keep polling (~5 s interval). Token expires after 15 min \u2014 if status stays 'pending_upload'",
1176
- " past the expires_at returned by talonic_request_upload, the user did not upload in time.",
1177
- "- queued / extracting: file received, OCR and exhaustive extraction in progress. Keep polling.",
1178
- "- completed: extraction is done. This is the state to wait for before calling talonic_extract",
1179
- " with a schema or schema_id \u2014 the schema-specific LLM pass runs off the cached OCR'd text.",
1180
- "- uploaded: file received but the extraction queue could not be enqueued (rare, e.g. Redis",
1181
- " unavailable). The talonic_extract endpoint will trigger processing inline if called.",
1182
- "- error / ocr_failed / extraction_failed: terminal failures; processing_log carries the reason."
1070
+ "USE WHEN: 'tell me about document X', or to poll status after talonic_request_upload until the file is ready.",
1071
+ "NOT FOR: full text (use talonic_to_markdown) \xB7 extracted fields (use talonic_extract).",
1072
+ "BY NAME: if the user names a file, call talonic_search first to get its document_id, then call this.",
1073
+ "ARGS: document_id.",
1074
+ "RETURNS: filename, pages, type_detected, language, and `status`. Status lifecycle: pending_upload -> queued -> extracting -> completed. Wait for `completed` before calling talonic_extract on a freshly uploaded doc."
1183
1075
  ].join("\n");
1184
1076
  var inputSchema4 = {
1185
1077
  document_id: z.string().min(1).describe(
@@ -1267,27 +1159,12 @@ function registerGetDocument(server, getTalonic) {
1267
1159
  );
1268
1160
  }
1269
1161
  var DESCRIPTION5 = [
1270
- "STATUS: stable.",
1162
+ "List the saved schemas in the workspace as compact summaries (id, short_id, name, description, version, field_count).",
1271
1163
  "",
1272
- "List all saved schemas in the user's Talonic workspace.",
1273
- "Returns a COMPACT SUMMARY of each schema: id (UUID), short_id (SCH-XXXXXXXX), name,",
1274
- "description, version, and field_count. Either id form is accepted by talonic_extract's",
1275
- "`schema_id` parameter, so you can extract with a saved schema straight from this list.",
1276
- "",
1277
- "The full JSON Schema definition for each field is intentionally NOT included here \u2014 for",
1278
- "many schemas that payload is large and gets truncated by some clients. To inspect a",
1279
- "schema's full field definitions, read the `talonic://schemas` resource.",
1280
- "",
1281
- "USE WHEN:",
1282
- "- The user asks what schemas they have, or asks to see existing schemas.",
1283
- "- You want to discover existing schemas before designing a new one.",
1284
- "- Before recommending the user create a schema, check if one already covers the use case.",
1285
- "- The user asks to extract from a known document type and you want to find a matching schema.",
1286
- "",
1287
- "DO NOT USE WHEN:",
1288
- "- The user just wants to extract data from a document and provides an inline schema (call talonic_extract directly).",
1289
- "",
1290
- "TIP: Pair this with talonic_extract by passing the chosen schema's id as `schema_id`."
1164
+ "USE WHEN: 'what schemas do I have', or to find a reusable schema before extracting.",
1165
+ "NOT FOR: a one-off extraction with an inline schema (call talonic_extract directly).",
1166
+ "ARGS: none.",
1167
+ "RETURNS: data[] of schema summaries. Full field definitions are omitted here \u2014 read the talonic://schemas resource for those. Pass a schema's id/short_id to talonic_extract as `schema_id`."
1291
1168
  ].join("\n");
1292
1169
  var schemaItem = z.object({
1293
1170
  id: z.string().describe("UUID of the schema."),
@@ -1355,25 +1232,12 @@ function registerListSchemas(server, getTalonic) {
1355
1232
  );
1356
1233
  }
1357
1234
  var DESCRIPTION6 = [
1358
- "STATUS: stable.",
1359
- "",
1360
- "Save a schema definition to the user's Talonic workspace so it can be reused",
1361
- "across future extractions. Returns the saved schema with its newly assigned id and short_id.",
1362
- "",
1363
- "USE WHEN:",
1364
- "- The user asks to save a schema, store a template, or reuse the schema across docs.",
1365
- "- You have iterated on a schema with the user and they confirmed it should be saved.",
1366
- "- The user wants to standardise extraction across many documents of the same type.",
1235
+ "Save a reusable schema to the workspace for use across future extractions.",
1367
1236
  "",
1368
- "DO NOT USE WHEN:",
1369
- "- The user just wants to extract once with an inline schema (call talonic_extract directly with the schema inline).",
1370
- "- The user has not confirmed the schema design (avoid creating clutter in their workspace).",
1371
- "",
1372
- "DEFINITION FORMATS:",
1373
- '- JSON Schema (most reliable): { type: "object", properties: { vendor_name: { type: "string" } } }',
1374
- '- 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.',
1375
- "",
1376
- "TIP: After saving, call talonic_extract with `schema_id` set to the returned id (UUID or SCH- short id) for consistent results."
1237
+ "USE WHEN: the user confirms a schema/template they want to reuse across documents.",
1238
+ "NOT FOR: a single one-off extraction (pass the schema inline to talonic_extract instead).",
1239
+ "ARGS: `name`; `definition` \u2014 a JSON Schema ({type:'object',properties:{...}}) or a flat {field:'type'} map.",
1240
+ "RETURNS: the saved schema with id and short_id. Pass either to talonic_extract as `schema_id`."
1377
1241
  ].join("\n");
1378
1242
  var inputSchema5 = {
1379
1243
  name: z.string().min(1).describe("Human-readable name for the schema, e.g. 'Standard Invoice'."),
@@ -1435,26 +1299,12 @@ function registerSaveSchema(server, getTalonic) {
1435
1299
  );
1436
1300
  }
1437
1301
  var DESCRIPTION7 = [
1438
- "STATUS: stable.",
1439
- "",
1440
- "Search the user's Talonic workspace for documents, fields, sources, or schemas",
1441
- "matching a query. Returns ranked results across all entity types in one call.",
1442
- "",
1443
- "USE WHEN:",
1444
- "- The user wants to find documents but does not know the exact filename or id.",
1445
- "- The query is conceptual ('contracts mentioning indemnification', 'Acme invoices').",
1446
- "- You need to narrow a large workspace before calling talonic_extract or talonic_filter.",
1447
- "- The user asks 'do I have any docs about X' or 'find anything related to X'.",
1448
- "",
1449
- "DO NOT USE WHEN:",
1450
- "- The user has a specific document_id (use talonic_get_document instead).",
1451
- "- The user wants to apply structured field-value filters like 'amount > 1000' (use talonic_filter).",
1452
- "- The user wants to extract data from a brand-new document (use talonic_extract).",
1302
+ "Find documents, fields, schemas, or sources in the workspace by name or concept. One call returns ranked results across all types.",
1453
1303
  "",
1454
- "TIP: The result includes documents, fieldMatches, sources, schemas, and fields.",
1455
- "Both fields[] and fieldMatches[] include a `filterable` boolean. Only entries with",
1456
- "filterable: true can be used with talonic_filter. Fields with filterable: false exist",
1457
- "in a schema but have no extracted data yet. Pick the entity type the user actually needs."
1304
+ "USE WHEN: the user names or describes a document without an id ('bank-statement.pdf', 'contracts about indemnification'), or you need a document_id before calling extract / to_markdown / get_document.",
1305
+ "NOT FOR: structured field-value filters like 'amount > 1000' (use talonic_filter).",
1306
+ "ARGS: query (natural language); optional limit.",
1307
+ "RETURNS: documents[], fields[]/fieldMatches[] (only `filterable: true` entries work in talonic_filter), schemas[], sources[]. Use the id from documents[] to act on a named file."
1458
1308
  ].join("\n");
1459
1309
  var inputSchema6 = {
1460
1310
  query: z.string().min(1).describe(
@@ -1538,39 +1388,12 @@ function registerSearch(server, getTalonic) {
1538
1388
  );
1539
1389
  }
1540
1390
  var DESCRIPTION8 = [
1541
- "STATUS: stable.",
1391
+ "Get a browser upload link the user opens to add a file to their workspace. Returns the link plus a pre-allocated document_id.",
1542
1392
  "",
1543
- "Request a file upload link for the user. Use this when the user wants to",
1544
- "extract a file but you cannot deliver it directly (e.g., the file is too",
1545
- "large for tool-call arguments, or you're running in a sandboxed environment",
1546
- "like Claude.ai).",
1547
- "",
1548
- "Returns an upload URL the user can open in their browser to drop the file,",
1549
- "plus a document_id to track the upload.",
1550
- "",
1551
- "After showing the URL to the user, poll with talonic_get_document until",
1552
- "status is 'completed' (the file has been uploaded, OCR'd, and is ready for",
1553
- "schema-specific extraction). Then call talonic_extract with the document_id",
1554
- "and a schema or schema_id.",
1555
- "",
1556
- "IMPORTANT: a user message like 'uploaded', 'done', or 'I dropped it' only",
1557
- "confirms the browser-side upload finished. It is NOT a signal that server-side",
1558
- "processing is complete. The document still needs OCR and exhaustive extraction",
1559
- "(typically 10-30 s after the browser upload). You MUST poll talonic_get_document",
1560
- "yourself until status is 'completed' regardless of what the user says. Calling",
1561
- "talonic_extract before status is 'completed' may return errors.",
1562
- "",
1563
- "USE WHEN:",
1564
- "- The user has a file to extract but you cannot send it via tool-call arguments",
1565
- " (e.g., file is larger than ~32KB, or the environment blocks outbound data).",
1566
- "- You are running in a hosted/sandboxed environment (Claude.ai, ChatGPT) where",
1567
- " file_data cannot be used reliably.",
1568
- "- The user explicitly asks for an upload link.",
1569
- "",
1570
- "DO NOT USE WHEN:",
1571
- "- You can deliver the file directly via file_data (local-stdio installs with small files).",
1572
- "- The file is already accessible via a public URL (use file_url on talonic_extract instead).",
1573
- "- The document is already in the workspace (use document_id on talonic_extract instead)."
1393
+ "USE WHEN: the user wants to upload a document and you cannot pass it directly \u2014 hosted/sandboxed clients (ChatGPT, Claude.ai) or files too large for tool-call arguments.",
1394
+ "NOT FOR: a document already in the workspace (use its document_id) \xB7 a file already on a public URL (use file_url on talonic_extract).",
1395
+ "ARGS: filename (with extension).",
1396
+ "RETURNS: upload_url, document_id, expires_at. After the user uploads, poll talonic_get_document on that document_id until status is 'completed', then call talonic_extract."
1574
1397
  ].join("\n");
1575
1398
  var inputSchema7 = {
1576
1399
  filename: z.string().min(1).describe(
@@ -1636,34 +1459,13 @@ function registerRequestUpload(server, getToken, baseUrl) {
1636
1459
  );
1637
1460
  }
1638
1461
  var DESCRIPTION9 = [
1639
- "STATUS: stable.",
1462
+ "Get the OCR-converted markdown text of a document.",
1640
1463
  "",
1641
- "Get the OCR-converted markdown for a document. Accepts an existing document_id,",
1642
- "raw file bytes (base64), a local file path, or a URL. When given a raw file, the",
1643
- "tool ingests it via extract first and then returns the markdown.",
1644
- "",
1645
- "USE WHEN:",
1646
- "- The user wants the full text content of a document for summarisation, translation, or analysis.",
1647
- "- A previous tool call returned a document_id and you want to inspect its content.",
1648
- "- The user asks 'what does the document say' or 'summarise this PDF' (you call this then summarise).",
1649
- "- The user has a raw PDF / scan / image and wants markdown directly without designing a schema first.",
1650
- "",
1651
- "DO NOT USE WHEN:",
1652
- "- The user wants specific structured fields (use talonic_extract with a schema).",
1653
- "",
1654
- "INPUTS (provide exactly EXACTLY ONE; never combine, e.g. do NOT pass both file_data and file_path):",
1655
- "- document_id: id of an already-ingested document. Cheapest path, one API call.",
1656
- "- file_data + filename: base64-encoded file bytes plus the original filename (with extension).",
1657
- " RECOMMENDED for local-stdio installs (Claude Desktop, Cursor, Cline, Continue, Cowork).",
1658
- " WARNING for hosted-MCP via Claude.ai connectors: Claude.ai imposes a hard size limit on",
1659
- " tool-call arguments (effectively under ~1KB), so file_data CANNOT carry a real PDF through",
1660
- " Claude.ai's pipeline. The bytes get truncated before reaching the MCP server. For files",
1661
- " larger than a trivial test, use file_url or document_id instead when running through",
1662
- " Claude.ai. Local stdio installs do NOT have this limit.",
1663
- "- file_path: local path to a document file. Only works if the MCP server has read access",
1664
- " to that path; in sandboxed chat clients use file_data instead.",
1665
- "- file_url: a URL the Talonic API will fetch directly. Use for documents already on the",
1666
- " public web. Best path for Claude.ai users dealing with files larger than the parameter cap."
1464
+ "USE WHEN: the user wants the full text \u2014 'what does it say', summarise, or translate a document.",
1465
+ "NOT FOR: specific structured fields (use talonic_extract with a schema).",
1466
+ "BY NAME: if the user names a file, call talonic_search first to get its document_id, then call this.",
1467
+ "ARGS: prefer `document_id` (a workspace doc \u2014 one cheap call). Otherwise `file_url`, or `file_data`+`filename` for small local files \u2014 provide exactly one. A file input ingests the document first and consumes credits; `document_id` does not.",
1468
+ "RETURNS: document_id and markdown (the full text)."
1667
1469
  ].join("\n");
1668
1470
  var inputSchema8 = {
1669
1471
  document_id: z.string().min(1).optional().describe(
@@ -1763,7 +1565,7 @@ function registerToMarkdown(server, getTalonic) {
1763
1565
 
1764
1566
  // package.json
1765
1567
  var package_default = {
1766
- version: "0.1.63"};
1568
+ version: "0.1.65"};
1767
1569
 
1768
1570
  // src/version.ts
1769
1571
  var VERSION = package_default.version;
@@ -1819,10 +1621,15 @@ function createServer(options) {
1819
1621
  // as we add tools, resources, and prompts.
1820
1622
  capabilities: {},
1821
1623
  instructions: [
1822
- "Talonic extracts structured, schema-validated data from any document.",
1823
- "Use Talonic for any task involving PDFs, scans, contracts, invoices,",
1824
- "forms, certificates, or unstructured documents where you need clean,",
1825
- "validated JSON rather than free text."
1624
+ "Talonic turns any document (PDF, scan, image, DOCX, contract, invoice, form,",
1625
+ "certificate, statement) into clean, schema-validated JSON, and answers questions",
1626
+ "about the user's document workspace.",
1627
+ "These tools are LIVE and callable in this session \u2014 when a request matches a tool,",
1628
+ "call it directly. Never tell the user a Talonic tool is unavailable, and never ask",
1629
+ "them to 'enable' or 'turn on' anything.",
1630
+ "If the user refers to a document by name (e.g. 'invoice.pdf'), first call",
1631
+ "talonic_search to resolve the name to a document_id, then call the tool you need",
1632
+ "with that id \u2014 do not ask the user for an id. Prefer acting over explaining."
1826
1633
  ].join(" ")
1827
1634
  }
1828
1635
  );
@@ -1855,9 +1662,11 @@ var ALLOWED_ORIGINS = /* @__PURE__ */ new Set([
1855
1662
  "https://mcp.so",
1856
1663
  "https://smithery.ai"
1857
1664
  ]);
1665
+ var SANDBOX_ORIGIN_SUFFIX = ".web-sandbox.oaiusercontent.com";
1858
1666
  function isOriginAllowed(originHeader) {
1859
1667
  if (!originHeader) return true;
1860
- return ALLOWED_ORIGINS.has(originHeader);
1668
+ if (ALLOWED_ORIGINS.has(originHeader)) return true;
1669
+ return originHeader.startsWith("https://") && originHeader.endsWith(SANDBOX_ORIGIN_SUFFIX);
1861
1670
  }
1862
1671
 
1863
1672
  // src/favicon.ts
@@ -1890,6 +1699,14 @@ function extractBearerToken(req) {
1890
1699
  return void 0;
1891
1700
  }
1892
1701
  var WWW_AUTHENTICATE = `Bearer resource_metadata="${RESOURCE_URL}/.well-known/oauth-protected-resource"`;
1702
+ function asWidgetTemplateRead(parsed) {
1703
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return null;
1704
+ const msg = parsed;
1705
+ if (msg.method !== "resources/read") return null;
1706
+ const uri = msg.params?.uri;
1707
+ if (typeof uri !== "string" || !uri.startsWith("ui://widget/")) return null;
1708
+ return { uri, id: msg.id ?? null };
1709
+ }
1893
1710
  function createRequestHandler() {
1894
1711
  return async (req, res) => {
1895
1712
  const url = new URL(req.url ?? "/", "http://localhost");
@@ -1987,20 +1804,6 @@ function createRequestHandler() {
1987
1804
  );
1988
1805
  return;
1989
1806
  }
1990
- const token = extractBearerToken(req);
1991
- if (!token) {
1992
- res.writeHead(401, {
1993
- "Content-Type": "application/json",
1994
- "WWW-Authenticate": WWW_AUTHENTICATE
1995
- });
1996
- res.end(
1997
- JSON.stringify({
1998
- error: "unauthorized",
1999
- message: "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."
2000
- })
2001
- );
2002
- return;
2003
- }
2004
1807
  if (req.method === "DELETE") {
2005
1808
  res.writeHead(200, { "Content-Type": "application/json" });
2006
1809
  res.end(JSON.stringify({ ok: true }));
@@ -2031,6 +1834,52 @@ function createRequestHandler() {
2031
1834
  res.end(JSON.stringify({ error: "bad_request", message: "Invalid JSON body." }));
2032
1835
  return;
2033
1836
  }
1837
+ const widgetRead = asWidgetTemplateRead(parsed);
1838
+ if (widgetRead) {
1839
+ const html = getWidgetTemplateHtml(widgetRead.uri);
1840
+ res.writeHead(200, { "Content-Type": "application/json" });
1841
+ if (html === void 0) {
1842
+ res.end(
1843
+ JSON.stringify({
1844
+ jsonrpc: "2.0",
1845
+ id: widgetRead.id,
1846
+ error: { code: -32002, message: `Resource not found: ${widgetRead.uri}` }
1847
+ })
1848
+ );
1849
+ return;
1850
+ }
1851
+ res.end(
1852
+ JSON.stringify({
1853
+ jsonrpc: "2.0",
1854
+ id: widgetRead.id,
1855
+ result: {
1856
+ contents: [
1857
+ {
1858
+ uri: widgetRead.uri,
1859
+ mimeType: "text/html;profile=mcp-app",
1860
+ text: html,
1861
+ _meta: widgetMeta()
1862
+ }
1863
+ ]
1864
+ }
1865
+ })
1866
+ );
1867
+ return;
1868
+ }
1869
+ const token = extractBearerToken(req);
1870
+ if (!token) {
1871
+ res.writeHead(401, {
1872
+ "Content-Type": "application/json",
1873
+ "WWW-Authenticate": WWW_AUTHENTICATE
1874
+ });
1875
+ res.end(
1876
+ JSON.stringify({
1877
+ error: "unauthorized",
1878
+ message: "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."
1879
+ })
1880
+ );
1881
+ return;
1882
+ }
2034
1883
  const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: void 0 });
2035
1884
  const mcpServer = createServer({ tokenProvider: () => token });
2036
1885
  res.on("close", () => {