@talonic/mcp 0.1.74 → 0.1.76

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.
@@ -1863,6 +1863,332 @@ function registerGrowthTools(server, getToken, baseUrl) {
1863
1863
  async (args) => handleGrowthToolsUsage(getToken, baseUrl, args)
1864
1864
  );
1865
1865
  }
1866
+ var DEFAULT_BASE2 = "https://api.talonic.com";
1867
+ var TASK_STATUSES = ["available", "claimed", "submitted", "timed_out", "cancelled"];
1868
+ var taskId = z.string().uuid().describe("Agent task UUID.");
1869
+ var executionEpoch = z.number().int().min(1).max(2147483647).describe("Execution epoch returned by the successful claim. Stale epochs are rejected.");
1870
+ var status = z.enum(TASK_STATUSES).optional().describe("Optional task-status filter.");
1871
+ var limit = z.number().int().min(1).max(100).optional().describe("Page size (default 50).");
1872
+ var cursor = z.string().min(1).optional().describe("Opaque cursor from pagination.next_cursor.");
1873
+ var outputValue = z.object({
1874
+ value: z.json().describe("JSON value matching the field's declared data type."),
1875
+ confidence: z.number().min(0).max(1).optional().describe("Optional confidence from 0 to 1."),
1876
+ reasoning: z.string().max(4e3).optional().describe("Optional concise reasoning for this field, up to 4,000 characters.")
1877
+ });
1878
+ var outputs = z.record(z.string().min(1), outputValue).describe("Output field key to { value, confidence?, reasoning? }. Use only declared fields.");
1879
+ var listInput = { status, limit, cursor };
1880
+ var idInput = { task_id: taskId };
1881
+ var heartbeatInput = { task_id: taskId, execution_epoch: executionEpoch };
1882
+ var submitInput = {
1883
+ task_id: taskId,
1884
+ execution_epoch: executionEpoch,
1885
+ outputs,
1886
+ summary: z.string().max(4e3).optional().describe("Optional result summary, up to 4,000 characters.")
1887
+ };
1888
+ var adminCustomerId = z.string().uuid().describe("Explicit customer/workspace UUID. Payload calls never accept 'all'.");
1889
+ var adminReason = z.string().min(1).max(1e3).describe("Human-readable reason recorded with the cross-tenant access.");
1890
+ var adminTotp = z.string().regex(/^\d{6}$/, "TOTP code must contain exactly 6 digits").describe("Fresh 6-digit TOTP code for step-up authorization.");
1891
+ var adminPayloadAccessInput = {
1892
+ customer_id: adminCustomerId,
1893
+ reason: adminReason,
1894
+ totp_code: adminTotp
1895
+ };
1896
+ function apiUrl(baseUrl, path, query) {
1897
+ const base = (baseUrl ?? DEFAULT_BASE2).replace(/\/$/, "");
1898
+ const url = new URL(`${base}${path}`);
1899
+ for (const [key, value] of Object.entries(query ?? {})) {
1900
+ if (value !== void 0 && value !== "") url.searchParams.set(key, String(value));
1901
+ }
1902
+ return url.toString();
1903
+ }
1904
+ async function agentTaskRequest(getToken, baseUrl, request) {
1905
+ try {
1906
+ const response = await fetch(apiUrl(baseUrl, request.path, request.query), {
1907
+ method: request.method ?? "GET",
1908
+ headers: {
1909
+ Authorization: `Bearer ${getToken()}`,
1910
+ Accept: "application/json",
1911
+ ...request.body === void 0 ? {} : { "Content-Type": "application/json" },
1912
+ ...request.headers
1913
+ },
1914
+ ...request.body === void 0 ? {} : { body: JSON.stringify(request.body) }
1915
+ });
1916
+ if (!response.ok) {
1917
+ const body = await response.text().catch(() => "");
1918
+ return toolError(
1919
+ new Error(`Talonic API error: HTTP ${response.status}${body ? ` \u2014 ${body}` : ""}`)
1920
+ );
1921
+ }
1922
+ return jsonOk(await response.json());
1923
+ } catch (error) {
1924
+ return toolError(error);
1925
+ }
1926
+ }
1927
+ function listQuery(args) {
1928
+ return { status: args.status, limit: args.limit, cursor: args.cursor };
1929
+ }
1930
+ function adminHeaders(args) {
1931
+ return {
1932
+ "x-talonic-reason": args.reason,
1933
+ "x-step-up-code": args.totp_code
1934
+ };
1935
+ }
1936
+ function handleListAgentTasks(getToken, baseUrl, args) {
1937
+ return agentTaskRequest(getToken, baseUrl, {
1938
+ path: "/v1/agent-tasks",
1939
+ query: listQuery(args)
1940
+ });
1941
+ }
1942
+ function handleGetAgentTask(getToken, baseUrl, args) {
1943
+ return agentTaskRequest(getToken, baseUrl, {
1944
+ path: `/v1/agent-tasks/${encodeURIComponent(args.task_id)}`
1945
+ });
1946
+ }
1947
+ function handleClaimAgentTask(getToken, baseUrl, args) {
1948
+ return agentTaskRequest(getToken, baseUrl, {
1949
+ method: "POST",
1950
+ path: `/v1/agent-tasks/${encodeURIComponent(args.task_id)}/claim`
1951
+ });
1952
+ }
1953
+ function handleHeartbeatAgentTask(getToken, baseUrl, args) {
1954
+ return agentTaskRequest(getToken, baseUrl, {
1955
+ method: "POST",
1956
+ path: `/v1/agent-tasks/${encodeURIComponent(args.task_id)}/heartbeat`,
1957
+ body: { execution_epoch: args.execution_epoch }
1958
+ });
1959
+ }
1960
+ function handleSubmitAgentTask(getToken, baseUrl, args) {
1961
+ return agentTaskRequest(getToken, baseUrl, {
1962
+ method: "POST",
1963
+ path: `/v1/agent-tasks/${encodeURIComponent(args.task_id)}/submit`,
1964
+ body: {
1965
+ execution_epoch: args.execution_epoch,
1966
+ outputs: args.outputs,
1967
+ ...args.summary === void 0 ? {} : { summary: args.summary }
1968
+ }
1969
+ });
1970
+ }
1971
+ async function probeAgentTaskAdminAccess(token, baseUrl) {
1972
+ try {
1973
+ const response = await fetch(apiUrl(baseUrl, "/v1/agent-tasks/admin/access"), {
1974
+ headers: { Authorization: `Bearer ${token}`, Accept: "application/json" },
1975
+ signal: AbortSignal.timeout(5e3)
1976
+ });
1977
+ return response.ok;
1978
+ } catch {
1979
+ return false;
1980
+ }
1981
+ }
1982
+ function handleAdminListAgentTasks(getToken, baseUrl, args) {
1983
+ return agentTaskRequest(getToken, baseUrl, {
1984
+ path: "/v1/agent-tasks/admin/tasks",
1985
+ query: { customerId: args.customer_id ?? "all", ...listQuery(args) }
1986
+ });
1987
+ }
1988
+ function handleAdminGetAgentTask(getToken, baseUrl, args) {
1989
+ return agentTaskRequest(getToken, baseUrl, {
1990
+ path: `/v1/agent-tasks/admin/tasks/${encodeURIComponent(args.task_id)}`,
1991
+ query: { customerId: args.customer_id },
1992
+ headers: adminHeaders(args)
1993
+ });
1994
+ }
1995
+ function handleAdminClaimAgentTask(getToken, baseUrl, args) {
1996
+ return agentTaskRequest(getToken, baseUrl, {
1997
+ method: "POST",
1998
+ path: `/v1/agent-tasks/admin/tasks/${encodeURIComponent(args.task_id)}/claim`,
1999
+ query: { customerId: args.customer_id },
2000
+ headers: adminHeaders(args)
2001
+ });
2002
+ }
2003
+ function handleAdminHeartbeatAgentTask(getToken, baseUrl, args) {
2004
+ return agentTaskRequest(getToken, baseUrl, {
2005
+ method: "POST",
2006
+ path: `/v1/agent-tasks/admin/tasks/${encodeURIComponent(args.task_id)}/heartbeat`,
2007
+ query: { customerId: args.customer_id },
2008
+ headers: adminHeaders(args),
2009
+ body: { execution_epoch: args.execution_epoch }
2010
+ });
2011
+ }
2012
+ function handleAdminSubmitAgentTask(getToken, baseUrl, args) {
2013
+ return agentTaskRequest(getToken, baseUrl, {
2014
+ method: "POST",
2015
+ path: `/v1/agent-tasks/admin/tasks/${encodeURIComponent(args.task_id)}/submit`,
2016
+ query: { customerId: args.customer_id },
2017
+ headers: adminHeaders(args),
2018
+ body: {
2019
+ execution_epoch: args.execution_epoch,
2020
+ outputs: args.outputs,
2021
+ ...args.summary === void 0 ? {} : { summary: args.summary }
2022
+ }
2023
+ });
2024
+ }
2025
+ var READ_ONLY2 = {
2026
+ readOnlyHint: true,
2027
+ destructiveHint: false,
2028
+ openWorldHint: false
2029
+ };
2030
+ var MUTATING = {
2031
+ readOnlyHint: false,
2032
+ destructiveHint: false,
2033
+ openWorldHint: false
2034
+ };
2035
+ var DESCRIPTIONS = {
2036
+ list: [
2037
+ "List Agent-stage tasks visible to this Talonic workspace credential.",
2038
+ "",
2039
+ "USE WHEN: looking for external-agent work to process; begin with status 'available'.",
2040
+ "NOT FOR: reading the immutable task payload (use talonic_get_agent_task) or taking a lease (use talonic_claim_agent_task).",
2041
+ "ARGS: optional status, limit, and cursor. RETURNS: metadata only plus pagination.next_cursor."
2042
+ ].join("\n"),
2043
+ get: [
2044
+ "Fetch one Agent-stage task's immutable input snapshot, instructions, and declared output contract. This disclosure is audited.",
2045
+ "",
2046
+ "USE WHEN: inspecting a listed task before deciding whether to process it.",
2047
+ "NOT FOR: acquiring the task (use talonic_claim_agent_task) or returning results (use talonic_submit_agent_task).",
2048
+ "ARGS: task_id. RETURNS: metadata, input_snapshot, output_contract, instructions, and timeout_fallthrough."
2049
+ ].join("\n"),
2050
+ claim: [
2051
+ "Claim an available Agent-stage task, or reclaim it after its lease expires.",
2052
+ "",
2053
+ "USE WHEN: ready to process a task. Save the returned execution_epoch and lease_expires_at.",
2054
+ "NOT FOR: merely inspecting work (use talonic_get_agent_task) or extending an active lease (use talonic_heartbeat_agent_task).",
2055
+ "A conflicting live claim returns HTTP 409. A successful claim returns the task payload."
2056
+ ].join("\n"),
2057
+ heartbeat: [
2058
+ "Extend the lease on a claimed Agent-stage task.",
2059
+ "",
2060
+ "USE WHEN: processing may continue past lease_expires_at; heartbeat before expiry using the epoch from claim.",
2061
+ "NOT FOR: acquiring a task (use talonic_claim_agent_task) or submitting finished outputs (use talonic_submit_agent_task).",
2062
+ "ARGS: task_id and execution_epoch. Stale or foreign claims return HTTP 409."
2063
+ ].join("\n"),
2064
+ submit: [
2065
+ "Submit declared output fields for a claimed Agent-stage task and resume the parked document.",
2066
+ "",
2067
+ "USE WHEN: processing is complete and every required output in output_contract is ready.",
2068
+ "NOT FOR: undeclared fields or partial lease maintenance (use talonic_heartbeat_agent_task).",
2069
+ "ARGS: task_id, execution_epoch, outputs keyed exactly by declared field key, and optional summary. The platform validates all fields and types transactionally before writing anything."
2070
+ ].join("\n")
2071
+ };
2072
+ function registerAgentTaskTools(server, getToken, baseUrl) {
2073
+ server.registerTool(
2074
+ "talonic_list_agent_tasks",
2075
+ {
2076
+ title: "List Agent Tasks",
2077
+ description: DESCRIPTIONS.list,
2078
+ inputSchema: listInput,
2079
+ annotations: { title: "List Agent Tasks", ...READ_ONLY2 }
2080
+ },
2081
+ async (args) => handleListAgentTasks(getToken, baseUrl, args)
2082
+ );
2083
+ server.registerTool(
2084
+ "talonic_get_agent_task",
2085
+ {
2086
+ title: "Get Agent Task",
2087
+ description: DESCRIPTIONS.get,
2088
+ inputSchema: idInput,
2089
+ annotations: { title: "Get Agent Task", ...READ_ONLY2 }
2090
+ },
2091
+ async (args) => handleGetAgentTask(getToken, baseUrl, args)
2092
+ );
2093
+ server.registerTool(
2094
+ "talonic_claim_agent_task",
2095
+ {
2096
+ title: "Claim Agent Task",
2097
+ description: DESCRIPTIONS.claim,
2098
+ inputSchema: idInput,
2099
+ annotations: { title: "Claim Agent Task", ...MUTATING }
2100
+ },
2101
+ async (args) => handleClaimAgentTask(getToken, baseUrl, args)
2102
+ );
2103
+ server.registerTool(
2104
+ "talonic_heartbeat_agent_task",
2105
+ {
2106
+ title: "Heartbeat Agent Task",
2107
+ description: DESCRIPTIONS.heartbeat,
2108
+ inputSchema: heartbeatInput,
2109
+ annotations: { title: "Heartbeat Agent Task", ...MUTATING }
2110
+ },
2111
+ async (args) => handleHeartbeatAgentTask(getToken, baseUrl, args)
2112
+ );
2113
+ server.registerTool(
2114
+ "talonic_submit_agent_task",
2115
+ {
2116
+ title: "Submit Agent Task",
2117
+ description: DESCRIPTIONS.submit,
2118
+ inputSchema: submitInput,
2119
+ annotations: { title: "Submit Agent Task", ...MUTATING }
2120
+ },
2121
+ async (args) => handleSubmitAgentTask(getToken, baseUrl, args)
2122
+ );
2123
+ }
2124
+ var adminIdInput = { task_id: taskId, ...adminPayloadAccessInput };
2125
+ var adminHeartbeatInput = {
2126
+ task_id: taskId,
2127
+ execution_epoch: executionEpoch,
2128
+ ...adminPayloadAccessInput
2129
+ };
2130
+ var adminSubmitInput = {
2131
+ task_id: taskId,
2132
+ execution_epoch: executionEpoch,
2133
+ outputs,
2134
+ summary: z.string().max(4e3).optional(),
2135
+ ...adminPayloadAccessInput
2136
+ };
2137
+ function registerAdminAgentTaskTools(server, getToken, baseUrl) {
2138
+ server.registerTool(
2139
+ "talonic_admin_list_agent_tasks",
2140
+ {
2141
+ title: "Admin: List Agent Tasks",
2142
+ description: "INTERNAL: list Agent-task metadata across all tenants or one named tenant. NOT FOR payload data; use talonic_admin_get_agent_task with an explicit tenant, reason, and TOTP code.",
2143
+ inputSchema: {
2144
+ customer_id: z.union([z.string().uuid(), z.literal("all")]).optional().describe("Tenant UUID, or 'all' (default) for cross-tenant metadata."),
2145
+ ...listInput
2146
+ },
2147
+ annotations: { title: "Admin: List Agent Tasks", ...READ_ONLY2 }
2148
+ },
2149
+ async (args) => handleAdminListAgentTasks(getToken, baseUrl, args)
2150
+ );
2151
+ server.registerTool(
2152
+ "talonic_admin_get_agent_task",
2153
+ {
2154
+ title: "Admin: Get Agent Task",
2155
+ description: "INTERNAL: fetch one Agent-task payload for an explicit tenant. This audited disclosure requires interactive OAuth, a reason, and fresh TOTP. NOT FOR cross-tenant metadata listing.",
2156
+ inputSchema: adminIdInput,
2157
+ annotations: { title: "Admin: Get Agent Task", ...READ_ONLY2 }
2158
+ },
2159
+ async (args) => handleAdminGetAgentTask(getToken, baseUrl, args)
2160
+ );
2161
+ server.registerTool(
2162
+ "talonic_admin_claim_agent_task",
2163
+ {
2164
+ title: "Admin: Claim Agent Task",
2165
+ description: "INTERNAL: claim or reclaim one Agent task in an explicit tenant. Requires interactive OAuth, reason, and fresh TOTP. NOT FOR metadata-only access.",
2166
+ inputSchema: adminIdInput,
2167
+ annotations: { title: "Admin: Claim Agent Task", ...MUTATING }
2168
+ },
2169
+ async (args) => handleAdminClaimAgentTask(getToken, baseUrl, args)
2170
+ );
2171
+ server.registerTool(
2172
+ "talonic_admin_heartbeat_agent_task",
2173
+ {
2174
+ title: "Admin: Heartbeat Agent Task",
2175
+ description: "INTERNAL: extend one claimed Agent-task lease in an explicit tenant. Requires interactive OAuth, reason, and fresh TOTP. NOT FOR acquiring a task.",
2176
+ inputSchema: adminHeartbeatInput,
2177
+ annotations: { title: "Admin: Heartbeat Agent Task", ...MUTATING }
2178
+ },
2179
+ async (args) => handleAdminHeartbeatAgentTask(getToken, baseUrl, args)
2180
+ );
2181
+ server.registerTool(
2182
+ "talonic_admin_submit_agent_task",
2183
+ {
2184
+ title: "Admin: Submit Agent Task",
2185
+ description: "INTERNAL: submit declared outputs for one claimed Agent task in an explicit tenant. Requires interactive OAuth, reason, and fresh TOTP. NOT FOR undeclared fields.",
2186
+ inputSchema: adminSubmitInput,
2187
+ annotations: { title: "Admin: Submit Agent Task", ...MUTATING }
2188
+ },
2189
+ async (args) => handleAdminSubmitAgentTask(getToken, baseUrl, args)
2190
+ );
2191
+ }
1866
2192
  var DESCRIPTION11 = [
1867
2193
  "Get the OCR-converted markdown text of a document.",
1868
2194
  "",
@@ -1968,9 +2294,384 @@ function registerToMarkdown(server, getTalonic) {
1968
2294
  );
1969
2295
  }
1970
2296
 
2297
+ // src/tools/_http.ts
2298
+ var DEFAULT_BASE3 = "https://api.talonic.com";
2299
+ function buildUrl(baseUrl, path, params = {}) {
2300
+ const qs = new URLSearchParams();
2301
+ for (const [k, v] of Object.entries(params)) {
2302
+ if (v === void 0 || v === "") continue;
2303
+ qs.set(k, String(v));
2304
+ }
2305
+ return `${baseUrl ?? DEFAULT_BASE3}${path}${qs.size ? `?${qs}` : ""}`;
2306
+ }
2307
+ async function apiJson(getToken, baseUrl, method, path, opts = {}) {
2308
+ const url = buildUrl(baseUrl, path, opts.params);
2309
+ const res = await fetch(url, {
2310
+ method,
2311
+ headers: {
2312
+ Authorization: `Bearer ${getToken()}`,
2313
+ Accept: "application/json",
2314
+ ...opts.body !== void 0 ? { "Content-Type": "application/json" } : {}
2315
+ },
2316
+ ...opts.body !== void 0 ? { body: JSON.stringify(opts.body) } : {}
2317
+ });
2318
+ if (!res.ok) {
2319
+ const text = await res.text().catch(() => "");
2320
+ throw new Error(`Talonic API error: HTTP ${res.status}${text ? ` \u2014 ${text}` : ""}`);
2321
+ }
2322
+ return await res.json();
2323
+ }
2324
+ async function runTool(fn) {
2325
+ try {
2326
+ return jsonOk(await fn());
2327
+ } catch (err) {
2328
+ return toolError(err);
2329
+ }
2330
+ }
2331
+
2332
+ // src/tools/fields.ts
2333
+ var MATURITIES = ["core", "proven", "candidate"];
2334
+ var maturityArg = z.enum(MATURITIES).optional().describe(
2335
+ "Filter by maturity: `core` (universal, fully trusted \u2014 safe to build on), `proven` (recurring, stable id), `candidate` (newly discovered, may still be merged or renamed)."
2336
+ );
2337
+ var fieldIdArg = z.string().uuid().optional().describe("Field UUID (from talonic_list_fields / talonic_search).");
2338
+ var fieldNameArg = z.string().min(1).optional().describe(
2339
+ "Field NAME instead of an id \u2014 resolved through canonical name, synonyms, merge aliases and the registry's spelling fold, then followed to the live concept. Use the user's wording ('Invoice No', 'Vertragsnummer')."
2340
+ );
2341
+ async function resolveFieldId(getToken, baseUrl, args) {
2342
+ if (args.field_id) return { id: args.field_id };
2343
+ const resolved = await apiJson(getToken, baseUrl, "GET", "/v1/fields/resolve", {
2344
+ params: { name: args.name, follow_redirects: true }
2345
+ });
2346
+ return {
2347
+ id: resolved.field.id,
2348
+ resolution: { matched_by: resolved.matched_by, redirected_from: resolved.redirected_from }
2349
+ };
2350
+ }
2351
+ var LIST_DESCRIPTION = [
2352
+ "List the workspace's Field Registry \u2014 the canonical concepts Talonic has discovered across every ingested document, each with a stable id, maturity level, data type, synonyms and occurrence count.",
2353
+ "",
2354
+ "USE WHEN: you need to know WHAT data exists before querying it, want to pick the right concept for a question, or need the exact field id for talonic_get_field / talonic_field_values.",
2355
+ "NOT FOR: locating a specific document (talonic_search) or filtering documents by a value (talonic_filter).",
2356
+ "",
2357
+ "ARGS: `search` (case-insensitive contains on name), `maturity` (core | proven | candidate \u2014 prefer `core`/`proven` for anything you will build on), `include_superseded` (default false: rows merged into another concept are hidden so you never see two ids for one concept), `limit`, `cursor`.",
2358
+ "RETURNS: data[] of { id, canonical_name, display_name, data_type, maturity, tier, synonyms, description, occurrence_count, superseded_by, links } plus cursor pagination."
2359
+ ].join("\n");
2360
+ var listFieldsInputSchema = {
2361
+ search: z.string().optional().describe("Case-insensitive contains match on canonical_name / display_name."),
2362
+ maturity: maturityArg,
2363
+ include_superseded: z.boolean().optional().describe("Include rows merged into a survivor (they carry `superseded_by`). Default false."),
2364
+ limit: z.number().int().min(1).max(100).optional().describe("Page size (default 20, max 100)."),
2365
+ cursor: z.string().optional().describe("Opaque cursor from pagination.next_cursor.")
2366
+ };
2367
+ async function handleListFields(getToken, baseUrl, args) {
2368
+ return runTool(
2369
+ () => apiJson(getToken, baseUrl, "GET", "/v1/fields", {
2370
+ params: {
2371
+ search: args.search,
2372
+ maturity: args.maturity,
2373
+ include_superseded: args.include_superseded,
2374
+ limit: args.limit,
2375
+ cursor: args.cursor
2376
+ }
2377
+ })
2378
+ );
2379
+ }
2380
+ var GET_DESCRIPTION = [
2381
+ "Get the CONCEPT CARD for one Field Registry field: what it means (curated description + extraction instruction), its synonyms and aliases, maturity, where it occurs (document/occurrence counts, first/last seen, document-type spread), its value distribution (top values with counts, distinct count, examples), schema usage, and identity links (superseded_by, absorbed concepts).",
2382
+ "",
2383
+ "USE WHEN: you must decide whether a field is the right concept for a question, need example values or the value shape before writing a filter, or hold a field NAME from the user and need the live concept behind it.",
2384
+ "NOT FOR: listing many fields (talonic_list_fields) or reading every value (talonic_field_values).",
2385
+ "",
2386
+ "ARGS: exactly one of `field_id` or `name`. Names are resolved through canonical name \u2192 spelling fold \u2192 merge aliases \u2192 synonyms (then case-insensitive fallbacks) and followed to the live concept; the response says which arm matched. `include_history: true` appends the curation trail (merges, renames, maturity moves).",
2387
+ "RETURNS: the card { id, canonical_name, maturity, data_type, definition, identity, occurrence, values, usage, links } plus `resolution` when a name was given and `history` when requested."
2388
+ ].join("\n");
2389
+ var getFieldInputSchema = {
2390
+ field_id: fieldIdArg,
2391
+ name: fieldNameArg,
2392
+ include_history: z.boolean().optional().describe(
2393
+ "Append the concept's curation history (tier changes, merges, renames), newest first."
2394
+ )
2395
+ };
2396
+ async function handleGetField(getToken, baseUrl, args) {
2397
+ if (!args.field_id && !args.name) return validationError("Provide `field_id` or `name`.");
2398
+ if (args.field_id && args.name)
2399
+ return validationError("Provide either `field_id` or `name`, not both.");
2400
+ return runTool(async () => {
2401
+ const { id, resolution } = await resolveFieldId(getToken, baseUrl, args);
2402
+ const card = await apiJson(
2403
+ getToken,
2404
+ baseUrl,
2405
+ "GET",
2406
+ `/v1/fields/${id}/card`,
2407
+ {
2408
+ params: { follow_redirects: true }
2409
+ }
2410
+ );
2411
+ const out = { ...card };
2412
+ if (resolution) out["resolution"] = resolution;
2413
+ if (args.include_history) {
2414
+ out["history"] = await apiJson(getToken, baseUrl, "GET", `/v1/fields/${id}/history`, {
2415
+ params: { limit: 50 }
2416
+ });
2417
+ }
2418
+ return out;
2419
+ });
2420
+ }
2421
+ var VALUES_DESCRIPTION = [
2422
+ "Read a field's CURRENT VALUES across documents, with provenance \u2014 one row per bound occurrence: document id + filename + type, the value, confidence, the raw name it was captured under, the verbatim source text, and the resolution band that bound it.",
2423
+ "",
2424
+ "USE WHEN: the user asks 'what are all the X across my documents', you need to tabulate or aggregate one concept across the corpus, or you want the evidence (source text + document) behind a value.",
2425
+ "NOT FOR: multi-field row-shaped queries over documents (talonic_filter) or one document's full field set (talonic_get_document).",
2426
+ "",
2427
+ "ARGS: exactly one of `field_id` or `name`; optional `document_id` (one document), `value` (case-insensitive contains filter), `limit` (max 100), `cursor`.",
2428
+ "RETURNS: { field_id, canonical_name, concept_ids, data[] of { occurrence_id, document_id, document_filename, value, confidence, provenance{ raw_field_name, source_text, resolved_by, needs_confirmation, via_redirect }, links }, pagination }. Rows are Sources-IAM filtered for the caller."
2429
+ ].join("\n");
2430
+ var fieldValuesInputSchema = {
2431
+ field_id: fieldIdArg,
2432
+ name: fieldNameArg,
2433
+ document_id: z.string().uuid().optional().describe("Only occurrences on this document."),
2434
+ value: z.string().optional().describe("Case-insensitive contains filter on the value text."),
2435
+ limit: z.number().int().min(1).max(100).optional().describe("Page size (default 20, max 100)."),
2436
+ cursor: z.string().optional().describe("Opaque cursor from pagination.next_cursor.")
2437
+ };
2438
+ async function handleFieldValues(getToken, baseUrl, args) {
2439
+ if (!args.field_id && !args.name) return validationError("Provide `field_id` or `name`.");
2440
+ if (args.field_id && args.name)
2441
+ return validationError("Provide either `field_id` or `name`, not both.");
2442
+ return runTool(async () => {
2443
+ const { id, resolution } = await resolveFieldId(getToken, baseUrl, args);
2444
+ const params = {
2445
+ document_id: args.document_id,
2446
+ value: args.value,
2447
+ limit: args.limit,
2448
+ cursor: args.cursor
2449
+ };
2450
+ const page = await apiJson(
2451
+ getToken,
2452
+ baseUrl,
2453
+ "GET",
2454
+ `/v1/fields/${id}/values`,
2455
+ { params }
2456
+ );
2457
+ return resolution ? { ...page, resolution } : page;
2458
+ });
2459
+ }
2460
+ function registerFieldTools(server, getToken, baseUrl) {
2461
+ server.registerTool(
2462
+ "talonic_list_fields",
2463
+ {
2464
+ title: "List registry fields",
2465
+ description: LIST_DESCRIPTION,
2466
+ inputSchema: listFieldsInputSchema,
2467
+ annotations: {
2468
+ readOnlyHint: true,
2469
+ destructiveHint: false,
2470
+ idempotentHint: true,
2471
+ openWorldHint: false
2472
+ }
2473
+ },
2474
+ async (args) => handleListFields(getToken, baseUrl, args)
2475
+ );
2476
+ server.registerTool(
2477
+ "talonic_get_field",
2478
+ {
2479
+ title: "Get a field's concept card",
2480
+ description: GET_DESCRIPTION,
2481
+ inputSchema: getFieldInputSchema,
2482
+ annotations: {
2483
+ readOnlyHint: true,
2484
+ destructiveHint: false,
2485
+ idempotentHint: true,
2486
+ openWorldHint: false
2487
+ }
2488
+ },
2489
+ async (args) => handleGetField(getToken, baseUrl, args)
2490
+ );
2491
+ server.registerTool(
2492
+ "talonic_field_values",
2493
+ {
2494
+ title: "Read a field's values across documents",
2495
+ description: VALUES_DESCRIPTION,
2496
+ inputSchema: fieldValuesInputSchema,
2497
+ annotations: {
2498
+ readOnlyHint: true,
2499
+ destructiveHint: false,
2500
+ idempotentHint: true,
2501
+ openWorldHint: false
2502
+ }
2503
+ },
2504
+ async (args) => handleFieldValues(getToken, baseUrl, args)
2505
+ );
2506
+ }
2507
+ function unwrap(res) {
2508
+ let result = res.content;
2509
+ if (typeof res.content === "string") {
2510
+ try {
2511
+ result = JSON.parse(res.content);
2512
+ } catch {
2513
+ result = res.content;
2514
+ }
2515
+ }
2516
+ const out = { tool: res.tool, result };
2517
+ if (res.citations?.length) out["citations"] = res.citations;
2518
+ if (res.artifacts?.length) out["artifacts"] = res.artifacts;
2519
+ if (res.cards?.length) out["cards"] = res.cards;
2520
+ return out;
2521
+ }
2522
+ var documentIdsArg = z.array(z.string().uuid()).max(1e3).optional().describe("Restrict to these document ids (hard filter, enforced server-side).");
2523
+ var FIND_DESCRIPTION = [
2524
+ "Locate the REAL data behind a natural-language concept before querying anything: semantic + lexical retrieval that resolves a phrase ('payment volume per transaction', 'counterparty', 'Vertragslaufzeit') to the registry fields, values, documents and text passages that carry it \u2014 even when the field is captured under a different name.",
2525
+ "",
2526
+ "USE WHEN: the user asks about a concept and you are not sure which field holds it, when talonic_list_fields / talonic_search came back empty or ambiguous, or when the answer may live in document prose rather than a captured cell.",
2527
+ "NOT FOR: reading a known field's values (talonic_field_values) or filtering by a known field (talonic_filter).",
2528
+ "",
2529
+ "ARGS: `query` (the concept, in the user's words), optional `top_k` (1\u201325, default 10), `document_ids` (hard scope).",
2530
+ "RETURNS: ranked planes \u2014 FIELDS (canonical_name, field ids/keys, maturity/tier, occurrence_count, sample values with their documents), VALUES, DOCUMENTS and PASSAGES \u2014 every item a ready handle for the next call. Read-only, no LLM cost."
2531
+ ].join("\n");
2532
+ var findDataInputSchema = {
2533
+ query: z.string().min(1).describe("The natural-language concept to locate."),
2534
+ top_k: z.number().int().min(1).max(25).optional().describe("Max results per plane (default 10)."),
2535
+ document_ids: documentIdsArg
2536
+ };
2537
+ async function handleFindData(getToken, baseUrl, args) {
2538
+ return runTool(async () => {
2539
+ const res = await apiJson(
2540
+ getToken,
2541
+ baseUrl,
2542
+ "POST",
2543
+ "/v1/agent/tools/find_data/invoke",
2544
+ {
2545
+ body: {
2546
+ args: {
2547
+ query: args.query,
2548
+ ...args.top_k !== void 0 ? { top_k: args.top_k } : {},
2549
+ ...args.document_ids?.length ? { document_scope: args.document_ids } : {}
2550
+ }
2551
+ }
2552
+ }
2553
+ );
2554
+ return unwrap(res);
2555
+ });
2556
+ }
2557
+ var LIST_TOOLS_DESCRIPTION = [
2558
+ "List the platform's agent tool registry \u2014 every retrieval, provenance and analysis primitive the in-product Talonic agent runs on (find_data, describe_data, query_data for read-only SQL over the extracted data, get_document_markdown, workspace_overview, \u2026) with its input schema and whether THIS credential may invoke it.",
2559
+ "",
2560
+ "USE WHEN: you want a capability talonic_* tools do not cover directly (e.g. SQL over the structured data, a workspace overview, cohort discovery) \u2014 list here, then call talonic_invoke_agent_tool with the tool name and its args.",
2561
+ "NOT FOR: discovering fields (talonic_list_fields / talonic_find_data) or documents (talonic_search) \u2014 those are shaped for you.",
2562
+ "",
2563
+ "ARGS: `only_invocable` (default true \u2014 hide tools this key cannot run), `include_schemas` (default true \u2014 include each tool's JSON input schema).",
2564
+ "RETURNS: { tools[] of { name, description, impact, capability, can_invoke, input_schema? }, invocable_count, totalCount }."
2565
+ ].join("\n");
2566
+ var listAgentToolsInputSchema = {
2567
+ only_invocable: z.boolean().optional().describe("Hide tools this credential cannot invoke. Default true."),
2568
+ include_schemas: z.boolean().optional().describe("Include each tool's JSON input schema. Default true.")
2569
+ };
2570
+ async function handleListAgentTools(getToken, baseUrl, args) {
2571
+ return runTool(async () => {
2572
+ const res = await apiJson(getToken, baseUrl, "GET", "/v1/agent/tools");
2573
+ const onlyInvocable = args.only_invocable ?? true;
2574
+ const includeSchemas = args.include_schemas ?? true;
2575
+ const tools = (res.tools ?? []).filter((t) => !onlyInvocable || t.can_invoke).map((t) => {
2576
+ const item = {
2577
+ name: t.name,
2578
+ description: t.description,
2579
+ impact: t.impact,
2580
+ capability: t.capability,
2581
+ can_invoke: t.can_invoke
2582
+ };
2583
+ if (includeSchemas) item["input_schema"] = t.input_schema;
2584
+ return item;
2585
+ });
2586
+ return {
2587
+ tools,
2588
+ invocable_count: res.invocable_count ?? tools.length,
2589
+ totalCount: res.totalCount ?? res.tools?.length ?? 0
2590
+ };
2591
+ });
2592
+ }
2593
+ var INVOKE_DESCRIPTION = [
2594
+ "Invoke ONE named tool from the platform's agent tool registry directly, with no model in the loop \u2014 you choose the arguments. This is how an external agent uses Talonic's retrieval and provenance while driving control flow itself (e.g. `query_data` for a read-only SQL SELECT over the extracted data, `describe_data` for the queryable field list, `get_document_markdown` to read a document's text).",
2595
+ "",
2596
+ "USE WHEN: talonic_list_agent_tools showed a tool with can_invoke: true that does what you need. Pass exactly the `args` its input_schema declares.",
2597
+ "NOT FOR: anything a dedicated talonic_* tool already does (prefer those \u2014 they are shaped for you).",
2598
+ "",
2599
+ "ARGS: `name` (tool name), `args` (object matching the tool's input_schema), optional `document_ids` (hard scope for scope-aware tools).",
2600
+ "RETURNS: { tool, result (the tool's parsed output), citations?, artifacts?, cards? }. Denied capabilities come back as an error naming the capability required; the platform re-checks every call."
2601
+ ].join("\n");
2602
+ var invokeAgentToolInputSchema = {
2603
+ name: z.string().min(1).describe("Tool name from talonic_list_agent_tools, e.g. `query_data`."),
2604
+ args: z.record(z.string(), z.unknown()).optional().describe("Arguments matching the tool's input_schema."),
2605
+ document_ids: documentIdsArg
2606
+ };
2607
+ async function handleInvokeAgentTool(getToken, baseUrl, args) {
2608
+ return runTool(async () => {
2609
+ const res = await apiJson(
2610
+ getToken,
2611
+ baseUrl,
2612
+ "POST",
2613
+ `/v1/agent/tools/${encodeURIComponent(args.name)}/invoke`,
2614
+ {
2615
+ body: {
2616
+ args: args.args ?? {},
2617
+ ...args.document_ids?.length ? { scope: { document_ids: args.document_ids } } : {}
2618
+ }
2619
+ }
2620
+ );
2621
+ return unwrap(res);
2622
+ });
2623
+ }
2624
+ function registerAgentRegistryTools(server, getToken, baseUrl) {
2625
+ server.registerTool(
2626
+ "talonic_find_data",
2627
+ {
2628
+ title: "Find the data behind a concept",
2629
+ description: FIND_DESCRIPTION,
2630
+ inputSchema: findDataInputSchema,
2631
+ annotations: {
2632
+ readOnlyHint: true,
2633
+ destructiveHint: false,
2634
+ idempotentHint: true,
2635
+ openWorldHint: false
2636
+ }
2637
+ },
2638
+ async (args) => handleFindData(getToken, baseUrl, args)
2639
+ );
2640
+ server.registerTool(
2641
+ "talonic_list_agent_tools",
2642
+ {
2643
+ title: "List the platform agent tools",
2644
+ description: LIST_TOOLS_DESCRIPTION,
2645
+ inputSchema: listAgentToolsInputSchema,
2646
+ annotations: {
2647
+ readOnlyHint: true,
2648
+ destructiveHint: false,
2649
+ idempotentHint: true,
2650
+ openWorldHint: false
2651
+ }
2652
+ },
2653
+ async (args) => handleListAgentTools(getToken, baseUrl, args)
2654
+ );
2655
+ server.registerTool(
2656
+ "talonic_invoke_agent_tool",
2657
+ {
2658
+ title: "Invoke a platform agent tool",
2659
+ description: INVOKE_DESCRIPTION,
2660
+ inputSchema: invokeAgentToolInputSchema,
2661
+ annotations: {
2662
+ readOnlyHint: true,
2663
+ destructiveHint: false,
2664
+ idempotentHint: false,
2665
+ openWorldHint: false
2666
+ }
2667
+ },
2668
+ async (args) => handleInvokeAgentTool(getToken, baseUrl, args)
2669
+ );
2670
+ }
2671
+
1971
2672
  // package.json
1972
2673
  var package_default = {
1973
- version: "0.1.74"};
2674
+ version: "0.1.76"};
1974
2675
 
1975
2676
  // src/version.ts
1976
2677
  var VERSION = package_default.version;
@@ -2062,6 +2763,15 @@ function createServer(options) {
2062
2763
  "with that id \u2014 do not ask the user for an id.",
2063
2764
  "talonic_search matches LITERAL keywords: query with one short singular term or an",
2064
2765
  "exact filename, never a sentence; on an empty result retry with a shorter keyword.",
2766
+ "The Field Registry is the source of truth for WHAT data exists: talonic_find_data",
2767
+ "resolves a concept in the user's words to the fields/documents that carry it,",
2768
+ "talonic_list_fields / talonic_get_field describe concepts (prefer maturity core or",
2769
+ "proven for anything you build on), talonic_field_values reads one concept across all",
2770
+ "documents with provenance. Anything else the in-product agent can do is reachable via",
2771
+ "talonic_list_agent_tools + talonic_invoke_agent_tool (e.g. query_data for SQL).",
2772
+ "For Agent-stage work, follow list -> get -> claim -> heartbeat while needed ->",
2773
+ "submit. Preserve the execution_epoch from claim and return only fields declared",
2774
+ "in the task output_contract; never continue after a lease or epoch conflict.",
2065
2775
  "Prefer acting over explaining."
2066
2776
  ].join(" ")
2067
2777
  }
@@ -2085,9 +2795,15 @@ function createServer(options) {
2085
2795
  registerGetPricing(server, getTalonic);
2086
2796
  registerGetUsage(server, getTalonic);
2087
2797
  registerRequestUpload(server, getToken, baseUrl);
2798
+ registerFieldTools(server, getToken, baseUrl);
2799
+ registerAgentRegistryTools(server, getToken, baseUrl);
2800
+ registerAgentTaskTools(server, getToken, baseUrl);
2088
2801
  if (options.includeGrowthTools) {
2089
2802
  registerGrowthTools(server, getToken, baseUrl);
2090
2803
  }
2804
+ if (options.includeAdminAgentTaskTools) {
2805
+ registerAdminAgentTaskTools(server, getToken, baseUrl);
2806
+ }
2091
2807
  registerSchemasResource(server, getTalonic);
2092
2808
  registerWebhooksResource(server, getToken, baseUrl);
2093
2809
  registerWidgets(server);
@@ -2131,6 +2847,19 @@ async function growthAccessCached(token, probe = probeGrowthAccess, now = Date.n
2131
2847
  growthProbeCache.set(token, { ok, expiresAt: now() + GROWTH_PROBE_TTL_MS });
2132
2848
  return ok;
2133
2849
  }
2850
+ var ADMIN_AGENT_TASK_PROBE_TTL_MS = 5 * 60 * 1e3;
2851
+ var adminAgentTaskProbeCache = /* @__PURE__ */ new Map();
2852
+ async function adminAgentTaskAccessCached(token, probe = probeAgentTaskAdminAccess, now = Date.now) {
2853
+ const hit = adminAgentTaskProbeCache.get(token);
2854
+ if (hit && hit.expiresAt > now()) return hit.ok;
2855
+ const ok = await probe(token);
2856
+ if (adminAgentTaskProbeCache.size >= 1e3) adminAgentTaskProbeCache.clear();
2857
+ adminAgentTaskProbeCache.set(token, {
2858
+ ok,
2859
+ expiresAt: now() + ADMIN_AGENT_TASK_PROBE_TTL_MS
2860
+ });
2861
+ return ok;
2862
+ }
2134
2863
  var RESOURCE_URL = process.env["MCP_RESOURCE_URL"] ?? "https://mcp.talonic.com";
2135
2864
  var AUTHORIZATION_SERVER = process.env["OAUTH_AUTHORIZATION_SERVER"] ?? "https://api.talonic.com";
2136
2865
  var APPS_CHALLENGE_TOKEN = process.env["OPENAI_APPS_CHALLENGE_TOKEN"] ?? "gnHvfQsKH6NVBNIeOWVK1vSt5QR2gsgBAIcXdSlpR_U";
@@ -2163,7 +2892,7 @@ function asWidgetTemplateRead(parsed) {
2163
2892
  if (typeof uri !== "string" || !uri.startsWith("ui://widget/")) return null;
2164
2893
  return { uri, id: msg.id ?? null };
2165
2894
  }
2166
- function createRequestHandler() {
2895
+ function createRequestHandler(options = {}) {
2167
2896
  return async (req, res) => {
2168
2897
  const url = new URL(req.url ?? "/", "http://localhost");
2169
2898
  const path = url.pathname;
@@ -2337,8 +3066,18 @@ function createRequestHandler() {
2337
3066
  return;
2338
3067
  }
2339
3068
  const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: void 0 });
2340
- const includeGrowthTools = await growthAccessCached(token);
2341
- const mcpServer = createServer({ tokenProvider: () => token, includeGrowthTools });
3069
+ const [includeGrowthTools, includeAdminAgentTaskTools] = await Promise.all([
3070
+ (options.growthAccess ?? growthAccessCached)(token),
3071
+ (options.adminAgentTaskAccess ?? ((currentToken) => adminAgentTaskAccessCached(
3072
+ currentToken,
3073
+ (candidate) => probeAgentTaskAdminAccess(candidate, process.env["TALONIC_BASE_URL"])
3074
+ )))(token)
3075
+ ]);
3076
+ const mcpServer = createServer({
3077
+ tokenProvider: () => token,
3078
+ includeGrowthTools,
3079
+ includeAdminAgentTaskTools
3080
+ });
2342
3081
  res.on("close", () => {
2343
3082
  void transport.close();
2344
3083
  void mcpServer.close();
@@ -2365,6 +3104,6 @@ if (isDirectInvocation()) {
2365
3104
  });
2366
3105
  }
2367
3106
 
2368
- export { createRequestHandler, growthAccessCached };
3107
+ export { adminAgentTaskAccessCached, createRequestHandler, growthAccessCached };
2369
3108
  //# sourceMappingURL=http-server.js.map
2370
3109
  //# sourceMappingURL=http-server.js.map