@talonic/mcp 0.1.35 → 0.1.37

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';
@@ -982,7 +984,7 @@ function registerToMarkdown(server, getTalonic) {
982
984
 
983
985
  // package.json
984
986
  var package_default = {
985
- version: "0.1.35"};
987
+ version: "0.1.37"};
986
988
 
987
989
  // src/version.ts
988
990
  var VERSION = package_default.version;
@@ -1101,165 +1103,185 @@ function extractBearerToken(req) {
1101
1103
  }
1102
1104
  return void 0;
1103
1105
  }
1104
- var sessions = /* @__PURE__ */ new Map();
1105
1106
  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) {
1107
+ function createRequestHandler() {
1108
+ const sessions = /* @__PURE__ */ new Map();
1109
+ return async (req, res) => {
1110
+ const url = new URL(req.url ?? "/", "http://localhost");
1111
+ const path = url.pathname;
1112
+ const incomingOrigin = req.headers["origin"];
1113
+ const incomingOriginValue = typeof incomingOrigin === "string" ? incomingOrigin : void 0;
1114
+ if (!isOriginAllowed(incomingOriginValue)) {
1115
+ res.writeHead(403, { "Content-Type": "application/json" });
1116
+ res.end(
1117
+ JSON.stringify({
1118
+ error: "origin_not_allowed",
1119
+ message: `Origin '${incomingOriginValue}' is not in the allowlist. Contact info@talonic.ai if you believe this is an error.`
1120
+ })
1121
+ );
1122
+ return;
1123
+ }
1124
+ if (path === "/health") {
1125
+ res.writeHead(200, { "Content-Type": "application/json" });
1126
+ res.end(JSON.stringify({ status: "ok", server: SERVER_NAME, version: VERSION }));
1127
+ return;
1128
+ }
1129
+ if (path === "/favicon.ico" || path === "/favicon.png") {
1130
+ if (FAVICON_BYTES.length === 0) {
1131
+ res.writeHead(404, { "Content-Type": "application/json" });
1132
+ res.end(
1133
+ JSON.stringify({
1134
+ error: "not_found",
1135
+ message: "Favicon asset not bundled with this build."
1136
+ })
1137
+ );
1138
+ return;
1139
+ }
1140
+ res.writeHead(200, {
1141
+ "Content-Type": "image/png",
1142
+ "Cache-Control": "public, max-age=86400, immutable",
1143
+ "Content-Length": String(FAVICON_BYTES.length)
1144
+ });
1145
+ res.end(FAVICON_BYTES);
1146
+ return;
1147
+ }
1148
+ if (path === "/.well-known/oauth-protected-resource") {
1149
+ res.writeHead(200, {
1150
+ "Content-Type": "application/json",
1151
+ "Cache-Control": "public, max-age=3600"
1152
+ });
1153
+ res.end(JSON.stringify(renderProtectedResourceMetadata()));
1154
+ return;
1155
+ }
1156
+ if (path === "/" && req.method === "GET") {
1157
+ const accept = String(req.headers["accept"] ?? "");
1158
+ if (!accept.includes("text/event-stream")) {
1159
+ res.writeHead(200, { "Content-Type": "application/json" });
1160
+ res.end(
1161
+ JSON.stringify({
1162
+ name: SERVER_NAME,
1163
+ version: VERSION,
1164
+ description: "Talonic MCP server. Extract structured, schema-validated data from any document.",
1165
+ mcp_endpoint: "/mcp",
1166
+ health_endpoint: "/health",
1167
+ oauth_protected_resource_endpoint: "/.well-known/oauth-protected-resource",
1168
+ 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.",
1169
+ docs: "https://talonic.com/docs/mcp"
1170
+ })
1171
+ );
1172
+ return;
1173
+ }
1174
+ }
1175
+ if (incomingOriginValue) {
1176
+ res.setHeader("Access-Control-Allow-Origin", incomingOriginValue);
1177
+ res.setHeader("Vary", "Origin");
1178
+ }
1179
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
1180
+ res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Mcp-Session-Id");
1181
+ res.setHeader("Access-Control-Expose-Headers", "Mcp-Session-Id");
1182
+ if (req.method === "OPTIONS") {
1183
+ res.writeHead(204);
1184
+ res.end();
1185
+ return;
1186
+ }
1187
+ if (path !== "/mcp" && path !== "/") {
1128
1188
  res.writeHead(404, { "Content-Type": "application/json" });
1129
1189
  res.end(
1130
1190
  JSON.stringify({
1131
1191
  error: "not_found",
1132
- message: "Favicon asset not bundled with this build."
1192
+ message: `No route for ${path}. Use /mcp (or /) for the MCP endpoint or /health for status.`
1133
1193
  })
1134
1194
  );
1135
1195
  return;
1136
1196
  }
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);
1197
+ if (req.method === "DELETE") {
1198
+ const sid = req.headers["mcp-session-id"];
1199
+ if (sid && sessions.has(sid)) {
1200
+ const session = sessions.get(sid);
1201
+ await session.transport.close();
1202
+ sessions.delete(sid);
1203
+ }
1204
+ res.writeHead(200, { "Content-Type": "application/json" });
1205
+ res.end(JSON.stringify({ ok: true }));
1206
+ return;
1197
1207
  }
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
1208
+ const token = extractBearerToken(req);
1209
+ if (!token) {
1210
+ res.writeHead(401, {
1211
+ "Content-Type": "application/json",
1212
+ "WWW-Authenticate": WWW_AUTHENTICATE
1213
+ });
1214
+ res.end(
1215
+ JSON.stringify({
1216
+ error: "unauthorized",
1217
+ 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."
1218
+ })
1219
+ );
1220
+ return;
1221
+ }
1222
+ const sessionId = req.headers["mcp-session-id"];
1223
+ if (sessionId && sessions.has(sessionId)) {
1224
+ const session = sessions.get(sessionId);
1225
+ session.tokenHolder.current = token;
1226
+ await session.transport.handleRequest(req, res);
1227
+ return;
1228
+ }
1229
+ const body = await new Promise((resolve) => {
1230
+ let data = "";
1231
+ req.on("data", (chunk) => {
1232
+ data += chunk.toString();
1233
+ });
1234
+ req.on("end", () => resolve(data));
1207
1235
  });
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();
1236
+ let parsed;
1237
+ try {
1238
+ parsed = JSON.parse(body);
1239
+ } catch {
1240
+ res.writeHead(400, { "Content-Type": "application/json" });
1241
+ res.end(JSON.stringify({ error: "bad_request", message: "Invalid JSON body." }));
1242
+ return;
1243
+ }
1244
+ if (sessionId && !isInitializeRequest(parsed)) {
1245
+ res.writeHead(404, { "Content-Type": "application/json" });
1246
+ res.end(
1247
+ JSON.stringify({
1248
+ error: "session_not_found",
1249
+ message: "Unknown session. Re-initialize without the Mcp-Session-Id header."
1250
+ })
1251
+ );
1252
+ return;
1253
+ }
1254
+ const transport = new StreamableHTTPServerTransport({
1255
+ sessionIdGenerator: () => randomUUID()
1227
1256
  });
1228
- req.on("end", () => resolve(data));
1229
- });
1230
- let parsed;
1257
+ const tokenHolder = { current: token };
1258
+ const mcpServer = createServer({ tokenProvider: () => tokenHolder.current });
1259
+ await mcpServer.connect(transport);
1260
+ await transport.handleRequest(req, res, parsed);
1261
+ const newSessionId = transport.sessionId;
1262
+ if (newSessionId) {
1263
+ sessions.set(newSessionId, { transport, tokenHolder });
1264
+ }
1265
+ };
1266
+ }
1267
+ function isDirectInvocation() {
1268
+ if (!process.argv[1]) return false;
1231
1269
  try {
1232
- parsed = JSON.parse(body);
1270
+ const argvPath = realpathSync(process.argv[1]);
1271
+ const metaPath = realpathSync(fileURLToPath(import.meta.url));
1272
+ return argvPath === metaPath;
1233
1273
  } catch {
1234
- res.writeHead(400, { "Content-Type": "application/json" });
1235
- res.end(JSON.stringify({ error: "bad_request", message: "Invalid JSON body." }));
1236
- return;
1274
+ return false;
1237
1275
  }
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;
1247
- }
1248
- const transport = new StreamableHTTPServerTransport({
1249
- sessionIdGenerator: () => randomUUID()
1276
+ }
1277
+ if (isDirectInvocation()) {
1278
+ const httpServer = createServer$1(createRequestHandler());
1279
+ httpServer.listen(PORT, () => {
1280
+ console.log(`${SERVER_NAME} ${VERSION} listening on http://0.0.0.0:${PORT}/mcp`);
1281
+ console.log(`Health check: http://0.0.0.0:${PORT}/health`);
1250
1282
  });
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
- });
1283
+ }
1284
+
1285
+ export { createRequestHandler };
1264
1286
  //# sourceMappingURL=http-server.js.map
1265
1287
  //# sourceMappingURL=http-server.js.map