@talonic/mcp 0.1.44 → 0.1.46

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/dist/index.js CHANGED
@@ -98,6 +98,186 @@ function registerWebhooksResource(server, getToken, baseUrl) {
98
98
  }
99
99
  );
100
100
  }
101
+
102
+ // src/widgets/extraction-result.ts
103
+ function getExtractionResultWidgetHtml() {
104
+ return WIDGET_HTML;
105
+ }
106
+ var WIDGET_HTML = `<!doctype html>
107
+ <html lang="en">
108
+ <head>
109
+ <meta charset="utf-8" />
110
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
111
+ <title>Talonic \u2014 Extraction Result</title>
112
+ <style>
113
+ :root {
114
+ --bg: #ffffff;
115
+ --fg: #111827;
116
+ --muted: #6b7280;
117
+ --border: #e5e7eb;
118
+ --accent: #4f46e5;
119
+ --good: #16a34a;
120
+ --warn: #d97706;
121
+ --bad: #dc2626;
122
+ }
123
+ @media (prefers-color-scheme: dark) {
124
+ :root {
125
+ --bg: #0f1115;
126
+ --fg: #f3f4f6;
127
+ --muted: #9ca3af;
128
+ --border: #1f2937;
129
+ }
130
+ }
131
+ html, body { margin: 0; padding: 0; background: var(--bg); color: var(--fg); font: 14px/1.5 ui-sans-serif, system-ui, -apple-system, sans-serif; }
132
+ .root { padding: 16px; }
133
+ .empty { color: var(--muted); padding: 24px; text-align: center; }
134
+ .header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 12px; }
135
+ .doc { font-weight: 600; }
136
+ .doc-meta { color: var(--muted); font-size: 12px; }
137
+ .confidence { display: flex; align-items: center; gap: 8px; font-size: 12px; color: var(--muted); }
138
+ .bar { width: 60px; height: 6px; background: var(--border); border-radius: 3px; overflow: hidden; }
139
+ .bar > span { display: block; height: 100%; background: var(--good); }
140
+ .bar.warn > span { background: var(--warn); }
141
+ .bar.bad > span { background: var(--bad); }
142
+ table { width: 100%; border-collapse: collapse; margin-top: 8px; }
143
+ th, td { text-align: left; padding: 8px 6px; border-bottom: 1px solid var(--border); vertical-align: top; font-size: 13px; }
144
+ th { color: var(--muted); font-weight: 500; font-size: 12px; }
145
+ .field-name { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; color: var(--muted); }
146
+ .field-val { font-variant-numeric: tabular-nums; word-break: break-word; }
147
+ .actions { margin-top: 12px; display: flex; gap: 8px; }
148
+ button { background: var(--bg); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; padding: 6px 10px; font: inherit; cursor: pointer; }
149
+ button:hover { border-color: var(--accent); }
150
+ </style>
151
+ </head>
152
+ <body>
153
+ <div id="root" class="root">
154
+ <div class="empty">Waiting for extraction result\u2026</div>
155
+ </div>
156
+ <script>
157
+ (function () {
158
+ var root = document.getElementById("root");
159
+
160
+ function escapeHtml(s) {
161
+ return String(s).replace(/[&<>"']/g, function (c) {
162
+ return { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c];
163
+ });
164
+ }
165
+
166
+ function confidenceClass(v) {
167
+ if (typeof v !== "number") return "";
168
+ if (v >= 0.85) return "";
169
+ if (v >= 0.7) return "warn";
170
+ return "bad";
171
+ }
172
+
173
+ function render(payload) {
174
+ if (!payload || typeof payload !== "object") {
175
+ root.innerHTML = '<div class="empty">No data.</div>';
176
+ return;
177
+ }
178
+ var doc = payload.document || {};
179
+ var data = payload.data || {};
180
+ var conf = payload.confidence || {};
181
+ var overall = typeof conf.overall === "number" ? conf.overall : null;
182
+ var fields = conf.fields || {};
183
+
184
+ var rows = Object.keys(data).map(function (k) {
185
+ var v = data[k];
186
+ var fc = fields[k];
187
+ var pct = typeof fc === "number" ? Math.round(fc * 100) + "%" : "\u2014";
188
+ var cls = confidenceClass(fc);
189
+ var bar = typeof fc === "number"
190
+ ? '<div class="bar ' + cls + '"><span style="width:' + Math.round(fc * 100) + '%"></span></div>'
191
+ : "";
192
+ return '<tr>'
193
+ + '<td class="field-name">' + escapeHtml(k) + '</td>'
194
+ + '<td class="field-val">' + escapeHtml(typeof v === "object" ? JSON.stringify(v) : v) + '</td>'
195
+ + '<td>' + bar + ' <span style="color:var(--muted);font-size:12px">' + pct + '</span></td>'
196
+ + '</tr>';
197
+ }).join("");
198
+
199
+ var overallHtml = overall === null
200
+ ? ""
201
+ : '<div class="confidence">'
202
+ + '<span>Overall</span>'
203
+ + '<div class="bar ' + confidenceClass(overall) + '"><span style="width:' + Math.round(overall * 100) + '%"></span></div>'
204
+ + '<span>' + Math.round(overall * 100) + '%</span>'
205
+ + '</div>';
206
+
207
+ root.innerHTML = ''
208
+ + '<div class="header">'
209
+ + ' <div>'
210
+ + ' <div class="doc">' + escapeHtml(doc.filename || "Document") + '</div>'
211
+ + ' <div class="doc-meta">'
212
+ + (doc.pages ? doc.pages + (doc.pages === 1 ? " page" : " pages") : "")
213
+ + (doc.type_detected ? " \xB7 " + escapeHtml(doc.type_detected) : "")
214
+ + (doc.language_detected ? " \xB7 " + escapeHtml(doc.language_detected) : "")
215
+ + ' </div>'
216
+ + ' </div>'
217
+ + overallHtml
218
+ + '</div>'
219
+ + '<table>'
220
+ + ' <thead><tr><th>Field</th><th>Value</th><th>Confidence</th></tr></thead>'
221
+ + ' <tbody>' + (rows || '<tr><td colspan="3" class="empty">No fields extracted.</td></tr>') + '</tbody>'
222
+ + '</table>'
223
+ + '<div class="actions">'
224
+ + ' <button id="copy-json">Copy JSON</button>'
225
+ + ' <button id="download-json">Download JSON</button>'
226
+ + '</div>';
227
+
228
+ var json = JSON.stringify(data, null, 2);
229
+ document.getElementById("copy-json").addEventListener("click", function () {
230
+ navigator.clipboard && navigator.clipboard.writeText(json);
231
+ });
232
+ document.getElementById("download-json").addEventListener("click", function () {
233
+ var blob = new Blob([json], { type: "application/json" });
234
+ var url = URL.createObjectURL(blob);
235
+ var a = document.createElement("a");
236
+ a.href = url;
237
+ a.download = (doc.filename || "extraction") + ".json";
238
+ a.click();
239
+ setTimeout(function () { URL.revokeObjectURL(url); }, 1000);
240
+ });
241
+ }
242
+
243
+ // Apps SDK delivers tool results via JSON-RPC notifications over postMessage.
244
+ // The host posts { method: "ui/notifications/tool-result", params: { structuredContent } }.
245
+ window.addEventListener("message", function (event) {
246
+ var msg = event.data;
247
+ if (!msg || msg.method !== "ui/notifications/tool-result") return;
248
+ var sc = msg.params && msg.params.structuredContent;
249
+ render(sc);
250
+ });
251
+ })();
252
+ </script>
253
+ </body>
254
+ </html>`;
255
+
256
+ // src/widgets/types.ts
257
+ var EXTRACTION_RESULT_WIDGET_URI = "ui://widget/extraction-result.html";
258
+ var EXTRACTION_RESULT_WIDGET_MIME = "text/html;profile=mcp-app";
259
+
260
+ // src/widgets/register.ts
261
+ function registerExtractionResultWidget(server) {
262
+ server.registerResource(
263
+ "extraction-result-widget",
264
+ EXTRACTION_RESULT_WIDGET_URI,
265
+ {
266
+ title: "Talonic Extraction Result",
267
+ description: "Inline view of extracted data, document metadata, and per-field confidence.",
268
+ mimeType: EXTRACTION_RESULT_WIDGET_MIME
269
+ },
270
+ async () => ({
271
+ contents: [
272
+ {
273
+ uri: EXTRACTION_RESULT_WIDGET_URI,
274
+ mimeType: EXTRACTION_RESULT_WIDGET_MIME,
275
+ text: getExtractionResultWidgetHtml()
276
+ }
277
+ ]
278
+ })
279
+ );
280
+ }
101
281
  function jsonOk(value) {
102
282
  const result = {
103
283
  content: [
@@ -195,7 +375,12 @@ var DESCRIPTION = [
195
375
  "- markdown: present only when `include_markdown: true`.",
196
376
  "- provenance: present only when `include_provenance: true`. Per-field source evidence:",
197
377
  " { field_name: { source_text, section, page } }. Useful for audit trails and citations.",
198
- "Cost, EUR price, and remaining credit balance are not surfaced in v0.1 and may appear in a later version."
378
+ "Cost, EUR price, and remaining credit balance are not surfaced in v0.1 and may appear in a later version.",
379
+ "",
380
+ "LARGE FILES / HOSTED ENVIRONMENTS:",
381
+ "For files larger than ~32KB, or when running in a hosted/sandboxed environment (Claude.ai, ChatGPT),",
382
+ "use talonic_request_upload first to get a browser upload link, then use the returned document_id",
383
+ "with this tool."
199
384
  ].join("\n");
200
385
  var inputSchema = {
201
386
  file_data: z.string().optional().describe(
@@ -323,6 +508,9 @@ function registerExtract(server, getTalonic) {
323
508
  readOnlyHint: false,
324
509
  destructiveHint: false,
325
510
  openWorldHint: true
511
+ },
512
+ _meta: {
513
+ "openai/outputTemplate": EXTRACTION_RESULT_WIDGET_URI
326
514
  }
327
515
  },
328
516
  async (args) => handleExtract(getTalonic(), args)
@@ -356,7 +544,8 @@ var DESCRIPTION2 = [
356
544
  "",
357
545
  "SCHEMA TYPING:",
358
546
  "- 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.",
359
- "- If the 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 (e.g. switching a field's `data_type` from `string` to `number`) that will make subsequent filter calls work correctly. Do not silently retry without flagging the warning.",
547
+ "- **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.",
548
+ "- **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.",
360
549
  "",
361
550
  "TIPS:",
362
551
  "- To discover available field names, call talonic_search first with a related query.",
@@ -819,7 +1008,10 @@ var outputSchema7 = {
819
1008
  displayName: z.string().optional(),
820
1009
  matchedValue: z.string().optional(),
821
1010
  documentCount: z.number().nullable().optional(),
822
- filterable: z.boolean().describe("Only filterable: true entries can be used with talonic_filter.")
1011
+ filterable: z.boolean().describe("Only filterable: true entries can be used with talonic_filter."),
1012
+ dataType: z.string().nullable().optional().describe(
1013
+ "Field's declared data type (e.g. `string`, `number`, `array`). Use this to guard numeric operators in `talonic_filter` (`gt`/`gte`/`lt`/`lte`/`between`) \u2014 they only resolve correctly when `dataType === 'number'`. `null` on non-materialized informational entries."
1014
+ )
823
1015
  })
824
1016
  ).describe(
825
1017
  "Field-level matches with a filterable flag indicating whether the entry can drive talonic_filter."
@@ -834,7 +1026,10 @@ var outputSchema7 = {
834
1026
  canonicalName: z.string().optional(),
835
1027
  displayName: z.string().optional(),
836
1028
  documentCount: z.number().nullable().optional(),
837
- filterable: z.boolean().optional()
1029
+ filterable: z.boolean().optional(),
1030
+ dataType: z.string().nullable().optional().describe(
1031
+ "Field's declared data type (e.g. `string`, `number`, `array`). Use this to guard numeric operators in `talonic_filter` (`gt`/`gte`/`lt`/`lte`/`between`) \u2014 they only resolve correctly when `dataType === 'number'`."
1032
+ )
838
1033
  })
839
1034
  ).describe(
840
1035
  "Field-registry entries matching the query. filterable: true entries are usable with talonic_filter."
@@ -869,6 +1064,88 @@ function registerSearch(server, getTalonic) {
869
1064
  );
870
1065
  }
871
1066
  var DESCRIPTION8 = [
1067
+ "STATUS: stable.",
1068
+ "",
1069
+ "Request a file upload link for the user. Use this when the user wants to",
1070
+ "extract a file but you cannot deliver it directly (e.g., the file is too",
1071
+ "large for tool-call arguments, or you're running in a sandboxed environment",
1072
+ "like Claude.ai).",
1073
+ "",
1074
+ "Returns an upload URL the user can open in their browser to drop the file,",
1075
+ "plus a document_id to track the upload.",
1076
+ "",
1077
+ "After showing the URL to the user, poll with talonic_get_document until",
1078
+ "status is 'uploaded', then proceed with talonic_extract using the document_id.",
1079
+ "",
1080
+ "USE WHEN:",
1081
+ "- The user has a file to extract but you cannot send it via tool-call arguments",
1082
+ " (e.g., file is larger than ~32KB, or the environment blocks outbound data).",
1083
+ "- You are running in a hosted/sandboxed environment (Claude.ai, ChatGPT) where",
1084
+ " file_data cannot be used reliably.",
1085
+ "- The user explicitly asks for an upload link.",
1086
+ "",
1087
+ "DO NOT USE WHEN:",
1088
+ "- You can deliver the file directly via file_data (local-stdio installs with small files).",
1089
+ "- The file is already accessible via a public URL (use file_url on talonic_extract instead).",
1090
+ "- The document is already in the workspace (use document_id on talonic_extract instead)."
1091
+ ].join("\n");
1092
+ var inputSchema7 = {
1093
+ filename: z.string().min(1).describe(
1094
+ "The name of the file being uploaded, including extension (e.g. 'invoice.pdf'). Used to pre-allocate the document and infer MIME type."
1095
+ )
1096
+ };
1097
+ var outputSchema8 = {
1098
+ document_id: z.string().describe("The pre-allocated document ID. Use with talonic_get_document to poll status, and with talonic_extract once uploaded."),
1099
+ upload_url: z.string().describe("URL the user should open in their browser to drop the file."),
1100
+ expires_at: z.string().describe("ISO 8601 timestamp when the upload link expires.")
1101
+ };
1102
+ async function handleRequestUpload(getToken, baseUrl, args) {
1103
+ try {
1104
+ const base = baseUrl ?? "https://api.talonic.com";
1105
+ const token = getToken();
1106
+ const res = await fetch(`${base}/v1/documents/upload-session`, {
1107
+ method: "POST",
1108
+ headers: {
1109
+ Authorization: `Bearer ${token}`,
1110
+ "Content-Type": "application/json",
1111
+ Accept: "application/json"
1112
+ },
1113
+ body: JSON.stringify({ filename: args.filename })
1114
+ });
1115
+ if (!res.ok) {
1116
+ const body = await res.text().catch(() => "");
1117
+ return toolError(
1118
+ new Error(`Talonic API error: HTTP ${res.status}${body ? ` \u2014 ${body}` : ""}`)
1119
+ );
1120
+ }
1121
+ const data = await res.json();
1122
+ return jsonOk({
1123
+ document_id: data.document_id,
1124
+ upload_url: data.upload_url,
1125
+ expires_at: data.expires_at
1126
+ });
1127
+ } catch (err) {
1128
+ return toolError(err);
1129
+ }
1130
+ }
1131
+ function registerRequestUpload(server, getToken, baseUrl) {
1132
+ server.registerTool(
1133
+ "talonic_request_upload",
1134
+ {
1135
+ title: "Request File Upload",
1136
+ description: DESCRIPTION8,
1137
+ inputSchema: inputSchema7,
1138
+ outputSchema: outputSchema8,
1139
+ annotations: {
1140
+ title: "Request File Upload",
1141
+ readOnlyHint: false,
1142
+ openWorldHint: true
1143
+ }
1144
+ },
1145
+ async (args) => handleRequestUpload(getToken, baseUrl, args)
1146
+ );
1147
+ }
1148
+ var DESCRIPTION9 = [
872
1149
  "STATUS: stable.",
873
1150
  "",
874
1151
  "Get the OCR-converted markdown for a document. Accepts an existing document_id,",
@@ -898,7 +1175,7 @@ var DESCRIPTION8 = [
898
1175
  "- file_url: a URL the Talonic API will fetch directly. Use for documents already on the",
899
1176
  " public web. Best path for Claude.ai users dealing with files larger than the parameter cap."
900
1177
  ].join("\n");
901
- var inputSchema7 = {
1178
+ var inputSchema8 = {
902
1179
  document_id: z.string().min(1).optional().describe(
903
1180
  "The Talonic document id whose markdown you want. Get this from a previous talonic_extract or talonic_search response."
904
1181
  ),
@@ -913,7 +1190,7 @@ var inputSchema7 = {
913
1190
  ),
914
1191
  file_url: z.string().optional().describe("URL to a document file. The Talonic API fetches it server-side.")
915
1192
  };
916
- var outputSchema8 = {
1193
+ var outputSchema9 = {
917
1194
  document_id: z.string().describe("ID of the document the markdown was extracted from."),
918
1195
  markdown: z.string().describe("OCR-converted markdown text content of the document."),
919
1196
  cost: z.object({
@@ -976,9 +1253,9 @@ function registerToMarkdown(server, getTalonic) {
976
1253
  "talonic_to_markdown",
977
1254
  {
978
1255
  title: "Document to Markdown",
979
- description: DESCRIPTION8,
980
- inputSchema: inputSchema7,
981
- outputSchema: outputSchema8,
1256
+ description: DESCRIPTION9,
1257
+ inputSchema: inputSchema8,
1258
+ outputSchema: outputSchema9,
982
1259
  annotations: {
983
1260
  title: "Document to Markdown",
984
1261
  readOnlyHint: false,
@@ -992,7 +1269,7 @@ function registerToMarkdown(server, getTalonic) {
992
1269
 
993
1270
  // package.json
994
1271
  var package_default = {
995
- version: "0.1.44"};
1272
+ version: "0.1.46"};
996
1273
 
997
1274
  // src/version.ts
998
1275
  var VERSION = package_default.version;
@@ -1063,8 +1340,10 @@ function createServer(options) {
1063
1340
  registerToMarkdown(server, getTalonic);
1064
1341
  registerExtract(server, getTalonic);
1065
1342
  registerGetBalance(server, getTalonic);
1343
+ registerRequestUpload(server, getToken, baseUrl);
1066
1344
  registerSchemasResource(server, getTalonic);
1067
1345
  registerWebhooksResource(server, getToken, baseUrl);
1346
+ registerExtractionResultWidget(server);
1068
1347
  return server;
1069
1348
  }
1070
1349