@talonic/mcp 0.1.36 → 0.1.38

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.
@@ -1,5 +1,7 @@
1
1
  import { createServer as createServer$1 } from 'http';
2
2
  import { randomUUID } from 'crypto';
3
+ import { realpathSync } from 'fs';
4
+ import { fileURLToPath } from 'url';
3
5
  import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
4
6
  import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js';
5
7
  import { Talonic, TalonicError } from '@talonic/node';
@@ -359,7 +361,8 @@ var DESCRIPTION2 = [
359
361
  "- 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.",
360
362
  "",
361
363
  "SCHEMA TYPING:",
362
- "- 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. The API returns a `warnings` array when a numeric operator is applied to a string-typed field.",
364
+ "- 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.",
365
+ "- 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.",
363
366
  "",
364
367
  "TIPS:",
365
368
  "- To discover available field names, call talonic_search first with a related query.",
@@ -418,7 +421,20 @@ var outputSchema2 = {
418
421
  limit: z.number().optional(),
419
422
  has_more: z.boolean().optional(),
420
423
  next_cursor: z.string().nullable().optional()
421
- }).optional().describe("Cursor-based pagination metadata.")
424
+ }).optional().describe("Cursor-based pagination metadata."),
425
+ warnings: z.array(
426
+ z.object({
427
+ code: z.string().optional().describe("Machine-readable warning code."),
428
+ message: z.string().optional().describe("Human-readable warning message."),
429
+ field: z.string().optional().describe("Canonical name of the field this warning applies to."),
430
+ field_id: z.string().optional().describe("UUID of the field this warning applies to."),
431
+ suggestion: z.string().optional().describe(
432
+ "Suggested mitigation, e.g. a recommended `data_type` change to make the query resolve correctly."
433
+ )
434
+ }).passthrough()
435
+ ).optional().describe(
436
+ "API warnings surfaced by the Talonic filter endpoint. Most commonly raised when a numeric operator is applied to a string-typed field, in which case the warning explains the lexicographic-comparison trap and suggests a schema-design change. Agents should surface these to the user rather than silently retrying."
437
+ )
422
438
  };
423
439
  async function handleFilter(talonic, args) {
424
440
  try {
@@ -982,7 +998,7 @@ function registerToMarkdown(server, getTalonic) {
982
998
 
983
999
  // package.json
984
1000
  var package_default = {
985
- version: "0.1.36"};
1001
+ version: "0.1.38"};
986
1002
 
987
1003
  // src/version.ts
988
1004
  var VERSION = package_default.version;
@@ -1101,165 +1117,185 @@ function extractBearerToken(req) {
1101
1117
  }
1102
1118
  return void 0;
1103
1119
  }
1104
- var sessions = /* @__PURE__ */ new Map();
1105
1120
  var WWW_AUTHENTICATE = `Bearer resource_metadata="${RESOURCE_URL}/.well-known/oauth-protected-resource"`;
1106
- var httpServer = createServer$1(async (req, res) => {
1107
- const url = new URL(req.url ?? "/", "http://localhost");
1108
- const path = url.pathname;
1109
- const incomingOrigin = req.headers["origin"];
1110
- const incomingOriginValue = typeof incomingOrigin === "string" ? incomingOrigin : void 0;
1111
- if (!isOriginAllowed(incomingOriginValue)) {
1112
- res.writeHead(403, { "Content-Type": "application/json" });
1113
- res.end(
1114
- JSON.stringify({
1115
- error: "origin_not_allowed",
1116
- message: `Origin '${incomingOriginValue}' is not in the allowlist. Contact info@talonic.ai if you believe this is an error.`
1117
- })
1118
- );
1119
- return;
1120
- }
1121
- if (path === "/health") {
1122
- res.writeHead(200, { "Content-Type": "application/json" });
1123
- res.end(JSON.stringify({ status: "ok", server: SERVER_NAME, version: VERSION }));
1124
- return;
1125
- }
1126
- if (path === "/favicon.ico" || path === "/favicon.png") {
1127
- if (FAVICON_BYTES.length === 0) {
1121
+ function createRequestHandler() {
1122
+ const sessions = /* @__PURE__ */ new Map();
1123
+ return async (req, res) => {
1124
+ const url = new URL(req.url ?? "/", "http://localhost");
1125
+ const path = url.pathname;
1126
+ const incomingOrigin = req.headers["origin"];
1127
+ const incomingOriginValue = typeof incomingOrigin === "string" ? incomingOrigin : void 0;
1128
+ if (!isOriginAllowed(incomingOriginValue)) {
1129
+ res.writeHead(403, { "Content-Type": "application/json" });
1130
+ res.end(
1131
+ JSON.stringify({
1132
+ error: "origin_not_allowed",
1133
+ message: `Origin '${incomingOriginValue}' is not in the allowlist. Contact info@talonic.ai if you believe this is an error.`
1134
+ })
1135
+ );
1136
+ return;
1137
+ }
1138
+ if (path === "/health") {
1139
+ res.writeHead(200, { "Content-Type": "application/json" });
1140
+ res.end(JSON.stringify({ status: "ok", server: SERVER_NAME, version: VERSION }));
1141
+ return;
1142
+ }
1143
+ if (path === "/favicon.ico" || path === "/favicon.png") {
1144
+ if (FAVICON_BYTES.length === 0) {
1145
+ res.writeHead(404, { "Content-Type": "application/json" });
1146
+ res.end(
1147
+ JSON.stringify({
1148
+ error: "not_found",
1149
+ message: "Favicon asset not bundled with this build."
1150
+ })
1151
+ );
1152
+ return;
1153
+ }
1154
+ res.writeHead(200, {
1155
+ "Content-Type": "image/png",
1156
+ "Cache-Control": "public, max-age=86400, immutable",
1157
+ "Content-Length": String(FAVICON_BYTES.length)
1158
+ });
1159
+ res.end(FAVICON_BYTES);
1160
+ return;
1161
+ }
1162
+ if (path === "/.well-known/oauth-protected-resource") {
1163
+ res.writeHead(200, {
1164
+ "Content-Type": "application/json",
1165
+ "Cache-Control": "public, max-age=3600"
1166
+ });
1167
+ res.end(JSON.stringify(renderProtectedResourceMetadata()));
1168
+ return;
1169
+ }
1170
+ if (path === "/" && req.method === "GET") {
1171
+ const accept = String(req.headers["accept"] ?? "");
1172
+ if (!accept.includes("text/event-stream")) {
1173
+ res.writeHead(200, { "Content-Type": "application/json" });
1174
+ res.end(
1175
+ JSON.stringify({
1176
+ name: SERVER_NAME,
1177
+ version: VERSION,
1178
+ description: "Talonic MCP server. Extract structured, schema-validated data from any document.",
1179
+ mcp_endpoint: "/mcp",
1180
+ health_endpoint: "/health",
1181
+ oauth_protected_resource_endpoint: "/.well-known/oauth-protected-resource",
1182
+ auth: "Provide a Talonic API key (tlnc_...) or an OAuth 2.1 access token via Authorization: Bearer ... header. API keys may also be passed via ?apiKey=tlnc_... query param; never put OAuth tokens in URLs.",
1183
+ docs: "https://talonic.com/docs/mcp"
1184
+ })
1185
+ );
1186
+ return;
1187
+ }
1188
+ }
1189
+ if (incomingOriginValue) {
1190
+ res.setHeader("Access-Control-Allow-Origin", incomingOriginValue);
1191
+ res.setHeader("Vary", "Origin");
1192
+ }
1193
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
1194
+ res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Mcp-Session-Id");
1195
+ res.setHeader("Access-Control-Expose-Headers", "Mcp-Session-Id");
1196
+ if (req.method === "OPTIONS") {
1197
+ res.writeHead(204);
1198
+ res.end();
1199
+ return;
1200
+ }
1201
+ if (path !== "/mcp" && path !== "/") {
1128
1202
  res.writeHead(404, { "Content-Type": "application/json" });
1129
1203
  res.end(
1130
1204
  JSON.stringify({
1131
1205
  error: "not_found",
1132
- message: "Favicon asset not bundled with this build."
1206
+ message: `No route for ${path}. Use /mcp (or /) for the MCP endpoint or /health for status.`
1133
1207
  })
1134
1208
  );
1135
1209
  return;
1136
1210
  }
1137
- res.writeHead(200, {
1138
- "Content-Type": "image/png",
1139
- "Cache-Control": "public, max-age=86400, immutable",
1140
- "Content-Length": String(FAVICON_BYTES.length)
1141
- });
1142
- res.end(FAVICON_BYTES);
1143
- return;
1144
- }
1145
- if (path === "/.well-known/oauth-protected-resource") {
1146
- res.writeHead(200, {
1147
- "Content-Type": "application/json",
1148
- "Cache-Control": "public, max-age=3600"
1149
- });
1150
- res.end(JSON.stringify(renderProtectedResourceMetadata()));
1151
- return;
1152
- }
1153
- if (path === "/") {
1154
- res.writeHead(200, { "Content-Type": "application/json" });
1155
- res.end(
1156
- JSON.stringify({
1157
- name: SERVER_NAME,
1158
- version: VERSION,
1159
- description: "Talonic MCP server. Extract structured, schema-validated data from any document.",
1160
- mcp_endpoint: "/mcp",
1161
- health_endpoint: "/health",
1162
- oauth_protected_resource_endpoint: "/.well-known/oauth-protected-resource",
1163
- auth: "Provide a Talonic API key (tlnc_...) or an OAuth 2.1 access token via Authorization: Bearer ... header. API keys may also be passed via ?apiKey=tlnc_... query param; never put OAuth tokens in URLs.",
1164
- docs: "https://talonic.com/docs/mcp"
1165
- })
1166
- );
1167
- return;
1168
- }
1169
- if (incomingOriginValue) {
1170
- res.setHeader("Access-Control-Allow-Origin", incomingOriginValue);
1171
- res.setHeader("Vary", "Origin");
1172
- }
1173
- res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
1174
- res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Mcp-Session-Id");
1175
- res.setHeader("Access-Control-Expose-Headers", "Mcp-Session-Id");
1176
- if (req.method === "OPTIONS") {
1177
- res.writeHead(204);
1178
- res.end();
1179
- return;
1180
- }
1181
- if (path !== "/mcp") {
1182
- res.writeHead(404, { "Content-Type": "application/json" });
1183
- res.end(
1184
- JSON.stringify({
1185
- error: "not_found",
1186
- message: `No route for ${path}. Use /mcp for the MCP endpoint or /health for status.`
1187
- })
1188
- );
1189
- return;
1190
- }
1191
- if (req.method === "DELETE") {
1192
- const sid = req.headers["mcp-session-id"];
1193
- if (sid && sessions.has(sid)) {
1194
- const session = sessions.get(sid);
1195
- await session.transport.close();
1196
- sessions.delete(sid);
1211
+ if (req.method === "DELETE") {
1212
+ const sid = req.headers["mcp-session-id"];
1213
+ if (sid && sessions.has(sid)) {
1214
+ const session = sessions.get(sid);
1215
+ await session.transport.close();
1216
+ sessions.delete(sid);
1217
+ }
1218
+ res.writeHead(200, { "Content-Type": "application/json" });
1219
+ res.end(JSON.stringify({ ok: true }));
1220
+ return;
1197
1221
  }
1198
- res.writeHead(200, { "Content-Type": "application/json" });
1199
- res.end(JSON.stringify({ ok: true }));
1200
- return;
1201
- }
1202
- const token = extractBearerToken(req);
1203
- if (!token) {
1204
- res.writeHead(401, {
1205
- "Content-Type": "application/json",
1206
- "WWW-Authenticate": WWW_AUTHENTICATE
1222
+ const token = extractBearerToken(req);
1223
+ if (!token) {
1224
+ res.writeHead(401, {
1225
+ "Content-Type": "application/json",
1226
+ "WWW-Authenticate": WWW_AUTHENTICATE
1227
+ });
1228
+ res.end(
1229
+ JSON.stringify({
1230
+ error: "unauthorized",
1231
+ 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."
1232
+ })
1233
+ );
1234
+ return;
1235
+ }
1236
+ const sessionId = req.headers["mcp-session-id"];
1237
+ if (sessionId && sessions.has(sessionId)) {
1238
+ const session = sessions.get(sessionId);
1239
+ session.tokenHolder.current = token;
1240
+ await session.transport.handleRequest(req, res);
1241
+ return;
1242
+ }
1243
+ const body = await new Promise((resolve) => {
1244
+ let data = "";
1245
+ req.on("data", (chunk) => {
1246
+ data += chunk.toString();
1247
+ });
1248
+ req.on("end", () => resolve(data));
1207
1249
  });
1208
- res.end(
1209
- JSON.stringify({
1210
- error: "unauthorized",
1211
- 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."
1212
- })
1213
- );
1214
- return;
1215
- }
1216
- const sessionId = req.headers["mcp-session-id"];
1217
- if (sessionId && sessions.has(sessionId)) {
1218
- const session = sessions.get(sessionId);
1219
- session.tokenHolder.current = token;
1220
- await session.transport.handleRequest(req, res);
1221
- return;
1222
- }
1223
- const body = await new Promise((resolve) => {
1224
- let data = "";
1225
- req.on("data", (chunk) => {
1226
- data += chunk.toString();
1250
+ let parsed;
1251
+ try {
1252
+ parsed = JSON.parse(body);
1253
+ } catch {
1254
+ res.writeHead(400, { "Content-Type": "application/json" });
1255
+ res.end(JSON.stringify({ error: "bad_request", message: "Invalid JSON body." }));
1256
+ return;
1257
+ }
1258
+ if (sessionId && !isInitializeRequest(parsed)) {
1259
+ res.writeHead(404, { "Content-Type": "application/json" });
1260
+ res.end(
1261
+ JSON.stringify({
1262
+ error: "session_not_found",
1263
+ message: "Unknown session. Re-initialize without the Mcp-Session-Id header."
1264
+ })
1265
+ );
1266
+ return;
1267
+ }
1268
+ const transport = new StreamableHTTPServerTransport({
1269
+ sessionIdGenerator: () => randomUUID()
1227
1270
  });
1228
- req.on("end", () => resolve(data));
1229
- });
1230
- let parsed;
1271
+ const tokenHolder = { current: token };
1272
+ const mcpServer = createServer({ tokenProvider: () => tokenHolder.current });
1273
+ await mcpServer.connect(transport);
1274
+ await transport.handleRequest(req, res, parsed);
1275
+ const newSessionId = transport.sessionId;
1276
+ if (newSessionId) {
1277
+ sessions.set(newSessionId, { transport, tokenHolder });
1278
+ }
1279
+ };
1280
+ }
1281
+ function isDirectInvocation() {
1282
+ if (!process.argv[1]) return false;
1231
1283
  try {
1232
- parsed = JSON.parse(body);
1284
+ const argvPath = realpathSync(process.argv[1]);
1285
+ const metaPath = realpathSync(fileURLToPath(import.meta.url));
1286
+ return argvPath === metaPath;
1233
1287
  } catch {
1234
- res.writeHead(400, { "Content-Type": "application/json" });
1235
- res.end(JSON.stringify({ error: "bad_request", message: "Invalid JSON body." }));
1236
- return;
1237
- }
1238
- if (sessionId && !isInitializeRequest(parsed)) {
1239
- res.writeHead(404, { "Content-Type": "application/json" });
1240
- res.end(
1241
- JSON.stringify({
1242
- error: "session_not_found",
1243
- message: "Unknown session. Re-initialize without the Mcp-Session-Id header."
1244
- })
1245
- );
1246
- return;
1288
+ return false;
1247
1289
  }
1248
- const transport = new StreamableHTTPServerTransport({
1249
- sessionIdGenerator: () => randomUUID()
1290
+ }
1291
+ if (isDirectInvocation()) {
1292
+ const httpServer = createServer$1(createRequestHandler());
1293
+ httpServer.listen(PORT, () => {
1294
+ console.log(`${SERVER_NAME} ${VERSION} listening on http://0.0.0.0:${PORT}/mcp`);
1295
+ console.log(`Health check: http://0.0.0.0:${PORT}/health`);
1250
1296
  });
1251
- const tokenHolder = { current: token };
1252
- const mcpServer = createServer({ tokenProvider: () => tokenHolder.current });
1253
- await mcpServer.connect(transport);
1254
- await transport.handleRequest(req, res, parsed);
1255
- const newSessionId = transport.sessionId;
1256
- if (newSessionId) {
1257
- sessions.set(newSessionId, { transport, tokenHolder });
1258
- }
1259
- });
1260
- httpServer.listen(PORT, () => {
1261
- console.log(`${SERVER_NAME} ${VERSION} listening on http://0.0.0.0:${PORT}/mcp`);
1262
- console.log(`Health check: http://0.0.0.0:${PORT}/health`);
1263
- });
1297
+ }
1298
+
1299
+ export { createRequestHandler };
1264
1300
  //# sourceMappingURL=http-server.js.map
1265
1301
  //# sourceMappingURL=http-server.js.map