toolsplice-core 0.0.1 → 0.0.2

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.
Files changed (111) hide show
  1. package/README.md +26 -17
  2. package/dist/abortable.d.ts +6 -0
  3. package/dist/abortable.js +50 -0
  4. package/dist/adaptive-read.d.ts +50 -0
  5. package/dist/adaptive-read.js +780 -0
  6. package/dist/answer-wait.d.ts +7 -0
  7. package/dist/answer-wait.js +45 -0
  8. package/dist/cache-reads.d.ts +18 -0
  9. package/dist/cache-reads.js +89 -0
  10. package/dist/calibration-ledger.d.ts +37 -0
  11. package/dist/calibration-ledger.js +148 -0
  12. package/dist/calibration-marker.d.ts +4 -0
  13. package/dist/calibration-marker.js +77 -0
  14. package/dist/catalog-setup.d.ts +33 -0
  15. package/dist/catalog-setup.js +89 -0
  16. package/dist/catalog.d.ts +10 -0
  17. package/dist/catalog.js +42 -0
  18. package/dist/checkpoint-files.d.ts +15 -0
  19. package/dist/checkpoint-files.js +99 -0
  20. package/dist/coalesce-reads.d.ts +6 -0
  21. package/dist/coalesce-reads.js +33 -0
  22. package/dist/contract-caller.d.ts +2 -1
  23. package/dist/contract-caller.js +35 -16
  24. package/dist/contract-schema.d.ts +3 -1
  25. package/dist/contract-schema.js +34 -4
  26. package/dist/contracts.d.ts +1 -0
  27. package/dist/contracts.js +5 -1
  28. package/dist/core.d.ts +31 -1
  29. package/dist/core.js +27 -0
  30. package/dist/db-final-answer.d.ts +9 -0
  31. package/dist/db-final-answer.js +62 -0
  32. package/dist/define.d.ts +78 -0
  33. package/dist/define.js +14 -0
  34. package/dist/final-answer-stores.d.ts +71 -0
  35. package/dist/final-answer-stores.js +72 -0
  36. package/dist/final-answer.d.ts +32 -0
  37. package/dist/final-answer.js +104 -0
  38. package/dist/impact.d.ts +48 -0
  39. package/dist/impact.js +71 -0
  40. package/dist/local-tool.d.ts +18 -0
  41. package/dist/local-tool.js +32 -0
  42. package/dist/mcp-apps.d.ts +53 -0
  43. package/dist/mcp-apps.js +32 -0
  44. package/dist/mcp-event-delivery.d.ts +98 -0
  45. package/dist/mcp-event-delivery.js +211 -0
  46. package/dist/mcp-extensions.d.ts +46 -0
  47. package/dist/mcp-extensions.js +200 -0
  48. package/dist/mcp-peer.d.ts +45 -0
  49. package/dist/mcp-peer.js +207 -0
  50. package/dist/mcp-server-card.d.ts +21 -0
  51. package/dist/mcp-server-card.js +54 -0
  52. package/dist/page-checkpoint.d.ts +71 -0
  53. package/dist/page-checkpoint.js +286 -0
  54. package/dist/page-read-gate.d.ts +15 -0
  55. package/dist/page-read-gate.js +48 -0
  56. package/dist/pattern.d.ts +1 -0
  57. package/dist/pattern.js +27 -5
  58. package/dist/read-pages.d.ts +25 -0
  59. package/dist/read-pages.js +85 -0
  60. package/dist/read-policy.d.ts +6 -0
  61. package/dist/read-policy.js +16 -0
  62. package/dist/read-steps.d.ts +12 -0
  63. package/dist/read-steps.js +36 -0
  64. package/dist/result-session.d.ts +109 -0
  65. package/dist/result-session.js +620 -0
  66. package/dist/route-checkpoint.d.ts +3 -0
  67. package/dist/route-checkpoint.js +80 -0
  68. package/dist/route-evaluation.d.ts +141 -0
  69. package/dist/route-evaluation.js +329 -0
  70. package/dist/row-groups.d.ts +17 -0
  71. package/dist/row-groups.js +79 -0
  72. package/dist/row-query.d.ts +62 -0
  73. package/dist/row-query.js +172 -0
  74. package/dist/rules.d.ts +30 -0
  75. package/dist/rules.js +72 -0
  76. package/dist/run-diagnostics.d.ts +75 -0
  77. package/dist/run-diagnostics.js +212 -0
  78. package/dist/search-fetch.d.ts +50 -0
  79. package/dist/search-fetch.js +264 -0
  80. package/dist/skill-files.d.ts +9 -0
  81. package/dist/skill-files.js +49 -0
  82. package/dist/splice-diagnostics.d.ts +4 -0
  83. package/dist/splice-diagnostics.js +24 -16
  84. package/dist/splice-recording.d.ts +29 -2
  85. package/dist/splice-recording.js +22 -5
  86. package/dist/splice.d.ts +98 -1
  87. package/dist/splice.js +225 -27
  88. package/dist/sqlite-checkpoint-store.d.ts +5 -0
  89. package/dist/sqlite-checkpoint-store.js +91 -0
  90. package/dist/sqlite-checkpoint-worker.js +115 -0
  91. package/dist/test-difference.d.ts +13 -0
  92. package/dist/test-difference.js +42 -0
  93. package/dist/testing.d.ts +122 -0
  94. package/dist/testing.js +261 -0
  95. package/dist/text-pages.d.ts +24 -0
  96. package/dist/text-pages.js +36 -0
  97. package/dist/tool-discovery.d.ts +59 -0
  98. package/dist/tool-discovery.js +136 -0
  99. package/dist/unevaluated.d.ts +7 -0
  100. package/dist/unevaluated.js +156 -0
  101. package/dist/version.d.ts +1 -1
  102. package/dist/version.js +1 -1
  103. package/dist/workflow-json.js +1 -1
  104. package/integrations/ai.d.mts +36 -0
  105. package/integrations/ai.mjs +178 -0
  106. package/integrations/call-options.mjs +9 -0
  107. package/integrations/langchain.d.mts +31 -0
  108. package/integrations/langchain.mjs +114 -0
  109. package/integrations/managed.mjs +154 -0
  110. package/integrations/types.d.mts +13 -0
  111. package/package.json +30 -1
@@ -0,0 +1,71 @@
1
+ /** Database adapters use an application-owned pool or database. Both SDKs store the
2
+ * same bounded JSON text to preserve JSON keys and numbers across SQL and BSON. */
3
+ export interface FinalAnswerRow {
4
+ identity: string;
5
+ payload: string | null;
6
+ }
7
+ export interface FinalAnswerStore {
8
+ read(job: string): Promise<FinalAnswerRow | null>;
9
+ claim(job: string, identity: string): Promise<boolean>;
10
+ complete(job: string, identity: string, payload: string): Promise<boolean>;
11
+ }
12
+ interface PgResult {
13
+ rowCount: number | null;
14
+ rows: Record<string, unknown>[];
15
+ }
16
+ interface PgQuery {
17
+ query(sql: string, values?: string[]): Promise<PgResult>;
18
+ }
19
+ interface PgPool extends PgQuery {
20
+ connect(): Promise<PgQuery & {
21
+ release(discard?: boolean): void;
22
+ }>;
23
+ }
24
+ export declare function postgresFinalAnswerStore(pool: PgPool): {
25
+ /** Run once in a migration; application workers need only SELECT, INSERT and UPDATE. */
26
+ initialize(): Promise<void>;
27
+ read(job: string): Promise<FinalAnswerRow>;
28
+ claim(job: string, identity: string): Promise<boolean>;
29
+ complete(job: string, identity: string, payload: string): Promise<boolean>;
30
+ };
31
+ interface MongoCollection {
32
+ findOne(filter: {
33
+ _id: string;
34
+ }, options: {
35
+ readPreference: "primary";
36
+ readConcern: {
37
+ level: "majority";
38
+ };
39
+ }): Promise<(FinalAnswerRow & {
40
+ _id: string;
41
+ }) | null>;
42
+ insertOne(row: FinalAnswerRow & {
43
+ _id: string;
44
+ }, options: MongoWrite): Promise<{
45
+ acknowledged: boolean;
46
+ }>;
47
+ updateOne(filter: {
48
+ _id: string;
49
+ identity: string;
50
+ payload: null;
51
+ }, update: {
52
+ $set: {
53
+ payload: string;
54
+ };
55
+ }, options: MongoWrite): Promise<{
56
+ acknowledged: boolean;
57
+ modifiedCount: number;
58
+ }>;
59
+ }
60
+ interface MongoWrite {
61
+ writeConcern: {
62
+ w: "majority";
63
+ j: true;
64
+ };
65
+ }
66
+ interface MongoDatabase {
67
+ databaseName: string;
68
+ collection(name: string): MongoCollection;
69
+ }
70
+ export declare function mongoFinalAnswerStore(database: MongoDatabase): FinalAnswerStore;
71
+ export {};
@@ -0,0 +1,72 @@
1
+ export function postgresFinalAnswerStore(pool) {
2
+ async function write(operation) {
3
+ const client = await pool.connect();
4
+ let discard = false;
5
+ try {
6
+ await client.query("BEGIN");
7
+ await client.query("SET LOCAL synchronous_commit = on");
8
+ const result = await operation(client);
9
+ await client.query("COMMIT");
10
+ return result;
11
+ }
12
+ catch (error) {
13
+ try {
14
+ await client.query("ROLLBACK");
15
+ }
16
+ catch {
17
+ discard = true;
18
+ }
19
+ throw error;
20
+ }
21
+ finally {
22
+ client.release(discard);
23
+ }
24
+ }
25
+ return {
26
+ /** Run once in a migration; application workers need only SELECT, INSERT and UPDATE. */
27
+ async initialize() {
28
+ await write(async (client) => {
29
+ await client.query("SELECT pg_advisory_xact_lock(1970037089, 1)");
30
+ await client.query("CREATE TABLE IF NOT EXISTS toolsplice_final_answers (job text PRIMARY KEY, identity text NOT NULL, payload text)");
31
+ });
32
+ },
33
+ async read(job) {
34
+ const { rows } = await pool.query("SELECT identity, payload FROM toolsplice_final_answers WHERE job = $1", [job]);
35
+ return rows[0] ?? null;
36
+ },
37
+ claim(job, identity) {
38
+ return write(async (client) => (await client.query("INSERT INTO toolsplice_final_answers (job, identity) VALUES ($1, $2) ON CONFLICT (job) DO NOTHING", [job, identity])).rowCount === 1);
39
+ },
40
+ complete(job, identity, payload) {
41
+ return write(async (client) => (await client.query("UPDATE toolsplice_final_answers SET payload = $3 WHERE job = $1 AND identity = $2 AND payload IS NULL", [job, identity, payload])).rowCount === 1);
42
+ },
43
+ };
44
+ }
45
+ export function mongoFinalAnswerStore(database) {
46
+ if (database.databaseName === "local")
47
+ throw new Error("Choose an application database with durable write concern.");
48
+ const collection = database.collection("toolsplice_final_answers");
49
+ const write = { writeConcern: { w: "majority", j: true } };
50
+ return {
51
+ read: (job) => collection.findOne({ _id: job }, { readPreference: "primary", readConcern: { level: "majority" } }),
52
+ async claim(job, identity) {
53
+ try {
54
+ const result = await collection.insertOne({ _id: job, identity, payload: null }, write);
55
+ if (!result.acknowledged)
56
+ throw new Error("Checkpoint claim was not acknowledged.");
57
+ return true;
58
+ }
59
+ catch (error) {
60
+ if (error?.code === 11000)
61
+ return false;
62
+ throw error;
63
+ }
64
+ },
65
+ async complete(job, identity, payload) {
66
+ const result = await collection.updateOne({ _id: job, identity, payload: null }, { $set: { payload } }, write);
67
+ if (!result.acknowledged)
68
+ throw new Error("Checkpoint save was not acknowledged.");
69
+ return result.modifiedCount === 1;
70
+ },
71
+ };
72
+ }
@@ -0,0 +1,32 @@
1
+ import type { FinalAnswerStore } from "./final-answer-stores.js";
2
+ import { databaseCheckpoint } from "./db-final-answer.js";
3
+ interface AnswerIdentity {
4
+ jobId: string;
5
+ /** Include the principal, inputs and version of the workflow. Only its fingerprint is stored. */
6
+ context: Record<string, unknown>;
7
+ schema: Record<string, unknown>;
8
+ }
9
+ export interface FinalAnswerOptions extends AnswerIdentity {
10
+ directory: string;
11
+ store?: never;
12
+ }
13
+ export interface DatabaseFinalAnswerOptions extends AnswerIdentity {
14
+ store: FinalAnswerStore;
15
+ directory?: never;
16
+ }
17
+ export type FinalAnswerStatus<T> = {
18
+ state: "missing" | "incomplete";
19
+ } | {
20
+ state: "saved";
21
+ answer: T;
22
+ };
23
+ /** One app-owned final answer. A durable claim precedes work and a validated save ends replay. */
24
+ export declare function finalAnswerCheckpoint<T = unknown>(options: FinalAnswerOptions): {
25
+ inspect(): FinalAnswerStatus<T>;
26
+ run(work: (save: (value: T) => T) => unknown, options?: {
27
+ waitMs?: number;
28
+ }): Promise<T>;
29
+ waitForResult(timeoutMs: number, signal?: AbortSignal): Promise<T>;
30
+ };
31
+ export declare function finalAnswerCheckpoint<T = unknown>(options: DatabaseFinalAnswerOptions): ReturnType<typeof databaseCheckpoint<T>>;
32
+ export {};
@@ -0,0 +1,104 @@
1
+ import { mkdirSync } from "node:fs";
2
+ import { join, resolve } from "node:path";
3
+ import { publish, read } from "./checkpoint-files.js";
4
+ import { createGuardCompiler } from "./contract-caller.js";
5
+ import { copyJson, jsonFingerprint } from "./workflow-json.js";
6
+ import { answerWaiter, validateWait } from "./answer-wait.js";
7
+ import { databaseCheckpoint } from "./db-final-answer.js";
8
+ export function finalAnswerCheckpoint(options) {
9
+ const { directory, store, jobId, context, schema } = options;
10
+ if ((store !== undefined
11
+ ? !store || directory !== undefined
12
+ : typeof directory !== "string" || !directory) ||
13
+ typeof jobId !== "string" ||
14
+ !jobId ||
15
+ !context ||
16
+ typeof context !== "object" ||
17
+ Array.isArray(context) ||
18
+ !schema ||
19
+ typeof schema !== "object" ||
20
+ Array.isArray(schema))
21
+ throw new TypeError("Expected one checkpoint directory or store, a job ID, context and answer schema.");
22
+ const version = 1;
23
+ const format = "toolsplice-final-answer";
24
+ const key = jsonFingerprint({ jobId, context, schema });
25
+ const job = jsonFingerprint(jobId);
26
+ const guard = createGuardCompiler()(copyJson(schema), "final_answer", "output");
27
+ const header = { format, version, key };
28
+ function check(value) {
29
+ const answer = copyJson(value, 65536);
30
+ if (!guard(answer))
31
+ throw new Error("Final answer does not match the declared schema.");
32
+ return answer;
33
+ }
34
+ if (store)
35
+ return databaseCheckpoint(store, job, jsonFingerprint(header), check);
36
+ const root = resolve(directory);
37
+ const stem = join(root, "answer-" + job);
38
+ function record(path) {
39
+ let value;
40
+ try {
41
+ value = read(path, 512 * 1024);
42
+ }
43
+ catch {
44
+ throw new Error("Invalid final answer checkpoint.");
45
+ }
46
+ if (value &&
47
+ (value.format !== format ||
48
+ value.version !== version ||
49
+ value.key !== key))
50
+ throw new Error("Final answer checkpoint identity or format mismatch.");
51
+ return value;
52
+ }
53
+ function inspect() {
54
+ const saved = record(stem + ".json");
55
+ if (saved) {
56
+ const answer = check(saved.answer);
57
+ if (saved.digest !== jsonFingerprint(answer))
58
+ throw new Error("Invalid final answer digest.");
59
+ return { state: "saved", answer };
60
+ }
61
+ return { state: record(stem + ".claim") ? "incomplete" : "missing" };
62
+ }
63
+ const waitForResult = answerWaiter(inspect);
64
+ async function run(work, options) {
65
+ if (options?.waitMs !== undefined)
66
+ validateWait(options.waitMs);
67
+ const cached = inspect();
68
+ if (cached.state === "saved")
69
+ return cached.answer;
70
+ mkdirSync(root, { recursive: true, mode: 0o700 });
71
+ if (!publish(stem + ".claim", header)) {
72
+ if (options?.waitMs !== undefined)
73
+ return waitForResult(options.waitMs);
74
+ const latest = inspect();
75
+ if (latest.state === "saved")
76
+ return latest.answer;
77
+ throw new Error("Final answer job is claimed without a saved answer. Reconcile before retrying.");
78
+ }
79
+ let open = true;
80
+ function save(candidate) {
81
+ if (!open)
82
+ throw new Error("Final answer run has ended.");
83
+ const answer = check(candidate);
84
+ const digest = jsonFingerprint(answer);
85
+ if (!publish(stem + ".json", { ...header, answer, digest })) {
86
+ const prior = inspect();
87
+ if (prior.state !== "saved" || jsonFingerprint(prior.answer) !== digest)
88
+ throw new Error("A different final answer is already saved.");
89
+ }
90
+ return answer;
91
+ }
92
+ try {
93
+ await work(save);
94
+ }
95
+ finally {
96
+ open = false;
97
+ }
98
+ const final = inspect();
99
+ if (final.state !== "saved")
100
+ throw new Error("The workflow ended without saving a final answer.");
101
+ return final.answer;
102
+ }
103
+ return { inspect, run, waitForResult };
104
+ }
@@ -0,0 +1,48 @@
1
+ import { createContractFromCatalog, type ContractSnapshot } from "./contracts.js";
2
+ import type { ToolResultLike } from "./extract.js";
3
+ import { type SpliceTestReport } from "./testing.js";
4
+ export interface SpliceImpactOptions {
5
+ sourceContract?: ContractSnapshot;
6
+ targetContract?: ContractSnapshot;
7
+ sourceCatalog?: Parameters<typeof createContractFromCatalog>[1];
8
+ targetCatalog?: Parameters<typeof createContractFromCatalog>[1];
9
+ /** Raw candidate MCP responses keyed by exact suite case name. */
10
+ sourceResults?: Record<string, ToolResultLike>;
11
+ }
12
+ export interface SpliceImpactReport {
13
+ format: "toolsplice-impact";
14
+ formatVersion: 1;
15
+ status: "fixtures-pass" | "regression" | "baseline-failed" | "inconclusive";
16
+ source: {
17
+ server: string;
18
+ tool: string;
19
+ };
20
+ target: {
21
+ server: string;
22
+ tool: string;
23
+ };
24
+ coverage: {
25
+ mappingCases: number;
26
+ executionCases: number;
27
+ expectedFailures: number;
28
+ exactArguments: number;
29
+ exactResults: number;
30
+ mockTargetResponses: number;
31
+ };
32
+ supplied: {
33
+ sourceContract: boolean;
34
+ targetContract: boolean;
35
+ sourceResultCases: string[];
36
+ };
37
+ unexercisedSourceResults: string[];
38
+ unavailable: {
39
+ side: "source" | "target";
40
+ reason: "absent-from-catalog" | "outside-snapshot";
41
+ }[];
42
+ baseline: SpliceTestReport;
43
+ candidate: SpliceTestReport | null;
44
+ networkCalls: 0;
45
+ liveToolCalls: 0;
46
+ }
47
+ /** Run the same expectations against a passing baseline and explicit candidate evidence. */
48
+ export declare function assessSpliceImpact(input: unknown, options: SpliceImpactOptions): Promise<SpliceImpactReport>;
package/dist/impact.js ADDED
@@ -0,0 +1,71 @@
1
+ import { createContractFromCatalog, parseContractSnapshot } from "./contracts.js";
2
+ import { parseSpliceSuite, runSpliceSuite } from "./testing.js";
3
+ import { copyJson, jsonObject } from "./workflow-json.js";
4
+ /** Run the same expectations against a passing baseline and explicit candidate evidence. */
5
+ export async function assessSpliceImpact(input, options) {
6
+ const suite = parseSpliceSuite(input);
7
+ if (!options || typeof options !== "object" || Array.isArray(options) || Object.keys(options).some(k => !["sourceContract", "targetContract", "sourceCatalog", "targetCatalog", "sourceResults"].includes(k)))
8
+ throw new Error("Supply candidate contracts or source results.");
9
+ const sourceResults = options.sourceResults === undefined ? {} : copyJson(options.sourceResults);
10
+ if (!jsonObject(sourceResults))
11
+ throw new Error("Candidate sourceResults must be an object keyed by case name.");
12
+ const names = new Set(suite.cases.map(c => c.name));
13
+ const sampleNames = Object.keys(sourceResults).sort();
14
+ if (sampleNames.some(name => {
15
+ const raw = sourceResults[name];
16
+ return !names.has(name) || !jsonObject(raw) ||
17
+ !["structuredContent", "content", "resultType", "isError"].some(key => Object.hasOwn(raw, key));
18
+ }))
19
+ throw new Error("Each candidate source result needs a matching suite case and a raw MCP response.");
20
+ if (suite.cases.some(c => c.transportFailure === "source" && Object.hasOwn(sourceResults, c.name)))
21
+ throw new Error("A source transport failure cannot also supply a candidate response.");
22
+ const unavailable = [];
23
+ const contracts = {};
24
+ for (const side of ["source", "target"]) {
25
+ const field = side === "source" ? "sourceContract" : "targetContract";
26
+ const catalog = side === "source" ? options.sourceCatalog : options.targetCatalog;
27
+ if (options[field] !== undefined && catalog !== undefined)
28
+ throw new Error("Choose one candidate contract or catalog per endpoint.");
29
+ if (options[field] === undefined && catalog === undefined)
30
+ continue;
31
+ const contract = catalog === undefined ? parseContractSnapshot(options[field])
32
+ : createContractFromCatalog({ name: suite.plan[side].server }, catalog);
33
+ if (contract.server.name !== suite.plan[side].server)
34
+ throw new Error("Candidate contract server identity differs from the plan.");
35
+ if (!contract.tools.some(t => t.name === suite.plan[side].tool))
36
+ unavailable.push({ side, reason: contract.selection === "all" ? "absent-from-catalog" : "outside-snapshot" });
37
+ contracts[field] = contract;
38
+ }
39
+ if (!contracts.sourceContract && !contracts.targetContract && !sampleNames.length)
40
+ throw new Error("Supply at least one candidate contract or source result.");
41
+ const baseline = await runSpliceSuite(suite);
42
+ const mappingCases = suite.cases.filter(c => c.mappingOnly).length;
43
+ const expectedFailures = suite.cases.filter(c => c.expect.status === "failed").length;
44
+ const endpoint = ({ server, tool }) => ({ server, tool });
45
+ const report = {
46
+ format: "toolsplice-impact", formatVersion: 1, status: "baseline-failed",
47
+ source: endpoint(suite.plan.source), target: endpoint(suite.plan.target),
48
+ coverage: { mappingCases, executionCases: suite.cases.length - mappingCases, expectedFailures,
49
+ exactArguments: suite.cases.filter(c => c.expect.arguments !== undefined).length,
50
+ exactResults: suite.cases.filter(c => c.expect.results !== undefined || c.expect.resultFingerprint !== undefined).length,
51
+ mockTargetResponses: suite.cases.reduce((n, c) => n + (c.targetResults?.length ?? 0), 0) },
52
+ supplied: { sourceContract: !!contracts.sourceContract, targetContract: !!contracts.targetContract, sourceResultCases: sampleNames },
53
+ unexercisedSourceResults: sampleNames, unavailable, baseline, candidate: null, networkCalls: 0, liveToolCalls: 0,
54
+ };
55
+ if (baseline.failed)
56
+ return report;
57
+ if (unavailable.length) {
58
+ report.status = unavailable.some(issue => issue.reason === "absent-from-catalog") ? "regression" : "inconclusive";
59
+ return report;
60
+ }
61
+ for (const c of suite.cases) {
62
+ if (Object.hasOwn(sourceResults, c.name))
63
+ c.sourceResult = sourceResults[c.name];
64
+ }
65
+ report.candidate = await runSpliceSuite(suite, contracts);
66
+ const used = new Set(report.candidate.cases.filter((c, i) => suite.cases[i].mappingOnly || c.actual.sourceCalls > 0).map(c => c.name));
67
+ report.unexercisedSourceResults = sampleNames.filter(name => !used.has(name));
68
+ report.status = report.candidate.failed ? "regression"
69
+ : expectedFailures === suite.cases.length || report.unexercisedSourceResults.length ? "inconclusive" : "fixtures-pass";
70
+ return report;
71
+ }
@@ -0,0 +1,18 @@
1
+ import { type BindingCallOptions } from "./execution.js";
2
+ import type { ToolAnnotations } from "./store.js";
3
+ export interface LocalToolDefinition {
4
+ name: string;
5
+ description?: string;
6
+ inputSchema: Record<string, unknown>;
7
+ outputSchema?: Record<string, unknown>;
8
+ annotations?: ToolAnnotations;
9
+ }
10
+ /** Adapt an application-owned function for the same mappings and guards as a remote tool. */
11
+ export declare function defineLocalTool<Args extends Record<string, unknown> = Record<string, unknown>, Value = unknown>(definition: LocalToolDefinition, handler: (args: Args, options?: BindingCallOptions) => Value | PromiseLike<Value>, options?: {
12
+ server?: string;
13
+ }): {
14
+ definition: LocalToolDefinition;
15
+ contract: import("./contracts.js").ContractSnapshot;
16
+ caller: import("./execution.js").ToolCaller;
17
+ execute: (args: Record<string, unknown>, options?: BindingCallOptions) => Promise<Value>;
18
+ };
@@ -0,0 +1,32 @@
1
+ import { createContractCaller, ContractValidationError, } from "./contract-caller.js";
2
+ import { createContractFromCatalog } from "./contracts.js";
3
+ import { invokeTool } from "./execution.js";
4
+ import { withCallDeadline } from "./abortable.js";
5
+ import { copyJson, jsonObject } from "./workflow-json.js";
6
+ /** Adapt an application-owned function for the same mappings and guards as a remote tool. */
7
+ export function defineLocalTool(definition, handler, options = {}) {
8
+ if (typeof handler !== "function")
9
+ throw new TypeError("A local tool needs a callable handler.");
10
+ const tool = copyJson(definition);
11
+ const contract = createContractFromCatalog({ name: options.server ?? "local" }, { tools: [tool] });
12
+ const caller = createContractCaller(async (request, callOptions) => {
13
+ if (!jsonObject(request.arguments))
14
+ throw new TypeError("Local tool arguments must be an object.");
15
+ const args = copyJson(request.arguments);
16
+ const value = await withCallDeadline(callOptions, "Local tool timed out.", (bounded) => handler(args, bounded));
17
+ return { structuredContent: copyJson(value) };
18
+ }, contract, { outputs: tool.outputSchema !== undefined });
19
+ async function execute(args, options) {
20
+ try {
21
+ return await invokeTool(caller, tool.name, args, options);
22
+ }
23
+ catch (error) {
24
+ options?.signal?.throwIfAborted();
25
+ if (error instanceof ContractValidationError ||
26
+ (error instanceof DOMException && error.name === "TimeoutError"))
27
+ throw error;
28
+ throw new Error("Local tool execution failed.", { cause: error });
29
+ }
30
+ }
31
+ return { definition: tool, contract, caller, execute };
32
+ }
@@ -0,0 +1,53 @@
1
+ export declare const MCP_APP_MIME_TYPE: "text/html;profile=mcp-app";
2
+ export interface McpToolUi {
3
+ resourceUri: string;
4
+ visibility?: ("model" | "app")[];
5
+ }
6
+ export interface McpAppResourceOptions {
7
+ uri: string;
8
+ name: string;
9
+ html: string;
10
+ description?: string;
11
+ /** Resource-local CSP, permissions and other rendering hints declared by the application. */
12
+ ui?: Record<string, unknown>;
13
+ ttlMs?: number;
14
+ cacheScope?: "private" | "public";
15
+ }
16
+ export declare function toolUi(input: McpToolUi): McpToolUi;
17
+ /** Read an application-owned HTML bundle by its exact registered URI. */
18
+ export declare function createMcpAppResource(options: McpAppResourceOptions): {
19
+ toolUi: McpToolUi;
20
+ definition: {
21
+ _meta?: undefined;
22
+ uri: string;
23
+ mimeType: "text/html;profile=mcp-app";
24
+ name: string;
25
+ description?: string | undefined;
26
+ } | {
27
+ _meta: {
28
+ ui: Record<string, unknown>;
29
+ };
30
+ uri: string;
31
+ mimeType: "text/html;profile=mcp-app";
32
+ name: string;
33
+ description?: string | undefined;
34
+ };
35
+ read(requestedUri: string): {
36
+ resultType: "complete";
37
+ ttlMs: number;
38
+ cacheScope: "private" | "public";
39
+ contents: ({
40
+ _meta?: undefined;
41
+ uri: string;
42
+ mimeType: "text/html;profile=mcp-app";
43
+ text: string;
44
+ } | {
45
+ _meta: {
46
+ ui: Record<string, unknown>;
47
+ };
48
+ uri: string;
49
+ mimeType: "text/html;profile=mcp-app";
50
+ text: string;
51
+ })[];
52
+ };
53
+ };
@@ -0,0 +1,32 @@
1
+ /** Server-side MCP Apps resources. The host renders HTML and enforces its sandbox. */
2
+ import { copyJson, jsonObject } from "./workflow-json.js";
3
+ export const MCP_APP_MIME_TYPE = "text/html;profile=mcp-app";
4
+ export function toolUi(input) {
5
+ const ui = copyJson(input);
6
+ if (!jsonObject(ui) || typeof ui.resourceUri !== "string" || !/^ui:\/\/[^\s\x00-\x1f\x7f]+$/u.test(ui.resourceUri))
7
+ throw new Error("An MCP App needs a ui:// resource URI.");
8
+ if (ui.visibility !== undefined && (!Array.isArray(ui.visibility) || !ui.visibility.length ||
9
+ new Set(ui.visibility).size !== ui.visibility.length || ui.visibility.some(v => v !== "model" && v !== "app")))
10
+ throw new Error("Tool visibility must list model, app, or both.");
11
+ return ui;
12
+ }
13
+ /** Read an application-owned HTML bundle by its exact registered URI. */
14
+ export function createMcpAppResource(options) {
15
+ const { uri, name, html, description, ui, ttlMs = 0, cacheScope = "private" } = copyJson(options);
16
+ const link = toolUi({ resourceUri: uri });
17
+ if (typeof name !== "string" || !name || typeof html !== "string" || !html.trim() ||
18
+ (description !== undefined && typeof description !== "string") || (ui !== undefined && !jsonObject(ui)) ||
19
+ !Number.isSafeInteger(ttlMs) || ttlMs < 0 || (cacheScope !== "private" && cacheScope !== "public"))
20
+ throw new Error("Invalid MCP App resource name, HTML, UI metadata or cache policy.");
21
+ const metadata = ui === undefined ? {} : { _meta: { ui } };
22
+ const base = { uri, mimeType: MCP_APP_MIME_TYPE, ...metadata };
23
+ return {
24
+ toolUi: link,
25
+ definition: copyJson({ ...base, name, ...(description === undefined ? {} : { description }) }),
26
+ read(requestedUri) {
27
+ if (requestedUri !== uri)
28
+ throw new Error("Unknown MCP App resource URI.");
29
+ return { resultType: "complete", ttlMs, cacheScope, contents: [copyJson({ ...base, text: html })] };
30
+ },
31
+ };
32
+ }
@@ -0,0 +1,98 @@
1
+ type JsonMap = Record<string, unknown>;
2
+ type Delivery = "poll" | "push" | "webhook";
3
+ export interface McpEventOccurrence extends JsonMap {
4
+ eventId: string;
5
+ name: string;
6
+ timestamp: string;
7
+ data: JsonMap;
8
+ cursor?: string | null;
9
+ }
10
+ /** The extension permits an omitted cursor everywhere a null cursor is accepted. */
11
+ export declare function eventCursor(value: unknown): string | null;
12
+ export declare function prepareEvent(descriptor: JsonMap, args: JsonMap, mode: Delivery): {
13
+ params: {
14
+ name: string;
15
+ arguments: JsonMap;
16
+ };
17
+ occurrence(value: unknown): McpEventOccurrence;
18
+ };
19
+ export declare function pushReceiver(descriptor: JsonMap, args: JsonMap, requestId: string | number): {
20
+ params: {
21
+ name: string;
22
+ arguments: JsonMap;
23
+ };
24
+ receive(message: unknown): {
25
+ type: "active";
26
+ cursor: string | null;
27
+ truncated: boolean;
28
+ heartbeatMs: number;
29
+ event?: undefined;
30
+ error?: undefined;
31
+ } | {
32
+ truncated?: undefined;
33
+ heartbeatMs?: undefined;
34
+ type: "event";
35
+ event: McpEventOccurrence;
36
+ cursor: string | null;
37
+ error?: undefined;
38
+ } | {
39
+ truncated?: undefined;
40
+ heartbeatMs?: undefined;
41
+ event?: undefined;
42
+ type: "heartbeat";
43
+ cursor: string | null;
44
+ error?: undefined;
45
+ } | {
46
+ truncated?: undefined;
47
+ heartbeatMs?: undefined;
48
+ event?: undefined;
49
+ cursor?: undefined;
50
+ type: "error";
51
+ error: JsonMap & {
52
+ code: number;
53
+ message: string;
54
+ };
55
+ } | {
56
+ truncated?: undefined;
57
+ heartbeatMs?: undefined;
58
+ event?: undefined;
59
+ cursor?: undefined;
60
+ type: "terminated";
61
+ error: JsonMap & {
62
+ code: number;
63
+ message: string;
64
+ };
65
+ };
66
+ };
67
+ export interface McpWebhookOptions {
68
+ secret: string;
69
+ /** During initial registration, omit the ID to accept signed verification challenges only. */
70
+ subscriptionId?: string;
71
+ }
72
+ type WebhookHeaders = Headers | Record<string, string | string[] | undefined>;
73
+ export declare function webhookReceiver(descriptor: JsonMap, args: JsonMap, options: McpWebhookOptions): Promise<(rawBody: Uint8Array, input: WebhookHeaders) => {
74
+ subscriptionId: string;
75
+ messageId: string;
76
+ type: "verification";
77
+ challenge: string;
78
+ } | {
79
+ subscriptionId: string;
80
+ messageId: string;
81
+ type: "event";
82
+ event: McpEventOccurrence;
83
+ cursor: string | null;
84
+ } | {
85
+ subscriptionId: string;
86
+ messageId: string;
87
+ type: "gap";
88
+ cursor: string | null;
89
+ } | {
90
+ subscriptionId: string;
91
+ messageId: string;
92
+ type: "terminated";
93
+ error: JsonMap & {
94
+ code: number;
95
+ message: string;
96
+ };
97
+ }>;
98
+ export {};