@talonic/mcp 0.1.43 → 0.1.45

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