@amalgm/tools 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/PURPOSE.md CHANGED
@@ -23,9 +23,14 @@ registry or execution implementation.
23
23
  - An **action** is one model-callable capability owned by exactly one tool.
24
24
  - A **Toolbox** is the sole catalog and mutation authority for one local state
25
25
  directory.
26
+ - A **tool deployment** is one immutable definition of a stable tool identity,
27
+ including its complete authoritative action set; activation appends the
28
+ deployment and moves that tool's current pointer atomically.
26
29
  - A **loadout** is a set of tool or action ids used to derive a read-only view
27
30
  of the Toolbox.
28
31
  - A **driver** executes actions for one tool type.
32
+ - An **MCP server** is a separately identified runtime endpoint that may expose
33
+ one or more tools; selecting a tool never changes that server's identity.
29
34
  - A **system tool** is an embedder-owned definition projected into the catalog;
30
35
  it is not user state.
31
36
  - A **notification** is one request to inform the current user; a channel
@@ -37,13 +42,14 @@ registry or execution implementation.
37
42
  `<tool-id>.<action-name>`.
38
43
  2. Tool ids are stable, globally unique within one Toolbox, and never change
39
44
  as a side effect of renaming display text.
40
- 3. A tool's portable definition is its artifact file: one file per tool,
41
- the tool and all of its actions together, never a second tool in the
42
- same file. The Toolbox database is a derived index maintained for
43
- runtime and realtime sync; SDK, CLI, and MCP adapters never keep
44
- parallel registries.
45
- 4. Applying a tool definition is atomic and authoritative for that tool: its
46
- supplied action set replaces the previous set completely.
45
+ 3. A tool's portable source of truth is its immutable deployment history and
46
+ current deployment pointer. SQLite tables, WAL files, catalog indexes, and
47
+ compatibility artifacts are local projections; SDK, CLI, MCP, HTTP, and UI
48
+ adapters never keep parallel registries.
49
+ 4. Applying a semantically changed tool definition mints one deployment and
50
+ atomically activates its complete action set. Applying equal semantics is a
51
+ no-op; rollback and deletion mint new deployments rather than rewriting or
52
+ removing history.
47
53
  5. Deleting a tool deletes all of its actions in the same transaction; an
48
54
  orphan action can never be observed.
49
55
  6. Disabled tools expose and execute no actions. Disabled actions are likewise
@@ -81,11 +87,34 @@ registry or execution implementation.
81
87
  20. Notification channels are host capabilities. Tools owns validation and
82
88
  result semantics; an injected channel adapter owns formatting, recipient
83
89
  lookup, credentials, and delivery.
90
+ 21. Reopening a Toolbox preserves the temporal fields of every semantically
91
+ unchanged system projection already present in its portable index; boot
92
+ never rewrites tracked bytes merely to stamp the current machine's time.
93
+ 22. The Toolbox exposes the versioned `deployment.activate` operation and its
94
+ exact definition through one Live surface; SQLite pages are never part of
95
+ that contract. A received activation materializes locally without echo,
96
+ retries are idempotent, and an existing deployment id can never acquire
97
+ different bytes.
98
+ 23. A host may separate the synced deployment directory from its machine-local
99
+ database. Amalgm Shell stores immutable deployment documents beneath
100
+ `users/<email>/toolbox/<tool-id>/deployments/` while keeping SQLite
101
+ coordination state below the machine boundary.
102
+ 24. A Chat preparation selects one catalog `revisionId` derived from exact
103
+ current deployment ids and system projections. Preparation either resolves
104
+ that exact revision or fails; it never silently substitutes newer tools.
105
+ 25. A host MCP source names both its server and its route. Tool identity,
106
+ action identity, server identity, and transport location are distinct even
107
+ when a first-party release currently maps them one-to-one.
108
+ 26. A scoped Toolbox MCP server advertises and calls only the selected loadout;
109
+ management actions are included only when the composing host asks for them.
84
110
 
85
111
  ## Predictable behavior
86
112
 
87
- Applying the same definition twice produces the same catalog. Applying a
88
- changed action set replaces the old set atomically. Selecting a whole tool
113
+ Applying the same definition twice produces the same catalog and no second
114
+ deployment. Reopening the
115
+ same system projection produces the same portable index bytes on every
116
+ machine. Applying a changed action set replaces the old set atomically.
117
+ Selecting a whole tool
89
118
  grants all of its enabled actions; selecting one action grants only that
90
119
  action. Disabling or deleting a tool immediately removes all of its actions
91
120
  from list and call surfaces. CLI arguments are passed directly to a process,
package/README.md CHANGED
@@ -36,6 +36,28 @@ verbatim when set, then `AMALGM_DIR/toolbox`, then the scoped layout
36
36
  `~/.amalgm/users/<scope>/toolbox`. Passing `stateDir` or `databaseFile`
37
37
  bypasses resolution entirely.
38
38
 
39
+ Platform hosts should separate portable deployment documents from local
40
+ coordination state:
41
+
42
+ ```js
43
+ const toolbox = new Toolbox({
44
+ deploymentDir: '/amalgm/users/person@example.com/toolbox',
45
+ databaseFile: '/machine-state/services/tools/tools.db',
46
+ });
47
+ ```
48
+
49
+ An intentional semantic change appends
50
+ `<deploymentDir>/<tool-id>/deployments/<deployment-id>.json` and atomically
51
+ advances the local head. The database, WAL, `toolbox.index.json`, and legacy
52
+ flat artifacts are projections and must not be synchronized. `catalog()`
53
+ exposes both a local numeric `revision` for presentation freshness and the
54
+ immutable `revisionId` that Chat must use for preparation.
55
+
56
+ `deploymentSurface()` implements the `amalgm.tools.deployments@1` Live
57
+ surface. Its operation is the shared `deployment.activate` envelope. Remote
58
+ application is idempotent and does not echo; `deploymentSnapshot()` and
59
+ `applyDeploymentSnapshot()` are the hydration/recovery boundary.
60
+
39
61
  ## CLI
40
62
 
41
63
  ```sh
@@ -0,0 +1,12 @@
1
+ import { Store } from './store.js';
2
+ import { ToolboxDeployments } from './toolbox-deployments.js';
3
+ import type { ActionRecord, ApplyResult, ToolDefinition, ToolRecord } from './types.js';
4
+ /** Normalize and deploy one authoritative user definition. */
5
+ declare function applyDefinition(options: {
6
+ definition: ToolDefinition;
7
+ store: Store;
8
+ deployments: ToolboxDeployments;
9
+ systemTools: readonly ToolRecord[];
10
+ systemActions: readonly ActionRecord[];
11
+ }): Promise<ApplyResult>;
12
+ export { applyDefinition };
@@ -0,0 +1,33 @@
1
+ import { portableRecordSemantic } from './artifacts.js';
2
+ import { normalizeDefinition } from './definition.js';
3
+ import { assertMcpNamesUnique, id } from './ids.js';
4
+ /** Normalize and deploy one authoritative user definition. */
5
+ async function applyDefinition(options) {
6
+ const { definition, store, deployments, systemTools, systemActions } = options;
7
+ const normalizedId = id(definition.id, 'tool.id', 64);
8
+ if (definition.origin === 'system')
9
+ throw new Error('System tools can only be supplied by the embedder');
10
+ if (systemTools.some((tool) => tool.id === normalizedId))
11
+ throw new Error(`System tool is immutable: ${normalizedId}`);
12
+ const existing = store.getTool(normalizedId);
13
+ const oldActions = new Map(store.actionsFor(normalizedId).map((action) => [action.id, action]));
14
+ const normalized = normalizeDefinition(definition, existing || undefined);
15
+ normalized.actions = normalized.actions.map((action) => ({
16
+ ...action, createdAt: oldActions.get(action.id)?.createdAt || action.createdAt,
17
+ }));
18
+ assertMcpNamesUnique([
19
+ ...systemActions,
20
+ ...store.catalog().actions.filter((action) => action.toolId !== normalized.tool.id),
21
+ ...normalized.actions,
22
+ ]);
23
+ const unchanged = existing && portableRecordSemantic(existing) === portableRecordSemantic(normalized.tool)
24
+ && normalized.actions.length === oldActions.size
25
+ && normalized.actions.every((action) => portableRecordSemantic(action)
26
+ === portableRecordSemantic(oldActions.get(action.id)));
27
+ if (unchanged) {
28
+ return { tool: existing, actions: [...oldActions.values()].sort((a, b) => a.id.localeCompare(b.id)) };
29
+ }
30
+ await deployments.activateLocal(normalized);
31
+ return normalized;
32
+ }
33
+ export { applyDefinition };
@@ -1,3 +1,4 @@
1
+ import type { ToolboxIndexDocument } from './artifacts.js';
1
2
  import type { ActionRecord, Catalog, ToolRecord } from './types.js';
2
3
  declare class ArtifactFiles {
3
4
  private readonly directory;
@@ -9,9 +10,10 @@ declare class ArtifactFiles {
9
10
  }): string;
10
11
  removeTool(toolId: string): void;
11
12
  writeIndex(catalog: Catalog): void;
13
+ readIndex(): ToolboxIndexDocument | null;
12
14
  /** Give every persisted user tool its portable artifact and refresh the
13
15
  * index. Additive only: a file for a tool this catalog does not know is
14
- * never deleted here — removal is an explicit mutation. */
16
+ * never deleted here — removal or snapshot hydration is explicit. */
15
17
  materialize(catalog: Catalog): void;
16
18
  /** Execute the legacy `toolbox.json` migration plan: per-tool artifacts
17
19
  * first, then the index, and only then the rename that retires the
@@ -2,8 +2,9 @@ import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { LEGACY_TOOLBOX_FILE_NAME, TOOLBOX_INDEX_FILE_NAME, artifactDocument, catalogIndexDocument, isToolArtifactDocument, legacyMigrationPlan, safeToolId, userArtifactFileName, } from './artifacts.js';
4
4
  /**
5
- * The host adapter for tool artifacts: it executes the pure documents and
6
- * plans from `artifacts.ts` against one state directory. Writes are atomic
5
+ * The host adapter for current compatibility projections: it executes the
6
+ * pure documents and plans from `artifacts.ts` against one local state
7
+ * directory. Writes are atomic
7
8
  * (tmp file + rename) and skipped when the bytes are unchanged, matching
8
9
  * Engine `lib/storage.js`.
9
10
  *
@@ -51,9 +52,16 @@ class ArtifactFiles {
51
52
  writeIndex(catalog) {
52
53
  writeJsonIfChanged(this.file(TOOLBOX_INDEX_FILE_NAME), catalogIndexDocument(catalog));
53
54
  }
55
+ readIndex() {
56
+ const value = readJson(this.file(TOOLBOX_INDEX_FILE_NAME));
57
+ if (!value || value.version !== 1 || !value.tools || typeof value.tools !== 'object'
58
+ || !value.toolActions || typeof value.toolActions !== 'object')
59
+ return null;
60
+ return value;
61
+ }
54
62
  /** Give every persisted user tool its portable artifact and refresh the
55
63
  * index. Additive only: a file for a tool this catalog does not know is
56
- * never deleted here — removal is an explicit mutation. */
64
+ * never deleted here — removal or snapshot hydration is explicit. */
57
65
  materialize(catalog) {
58
66
  for (const tool of catalog.tools) {
59
67
  if (tool.origin === 'system')
@@ -2,11 +2,11 @@ import type { ActionRecord, Catalog, ToolRecord } from './types.js';
2
2
  /**
3
3
  * Tool artifact format laws — the portable representation of a tool.
4
4
  *
5
- * One tool is one artifact file: the tool definition and every action it
6
- * owns travel together, and a file never carries a second tool. Artifact
7
- * files are the portable definition; the Toolbox database and
8
- * `toolbox.index.json` are derived caches. The format is ported byte-exact
9
- * from Engine `runtime/scripts/amalgm-mcp/toolbox/artifacts.js`.
5
+ * One compatibility artifact projects one current tool and every action it
6
+ * owns together; a file never carries a second tool. Immutable deployment
7
+ * documents are the portable source of truth. These artifacts, the Toolbox
8
+ * database, and `toolbox.index.json` are derived views retained for current
9
+ * Engine/UI readers.
10
10
  *
11
11
  * Pure laws only: nothing here touches the filesystem. `artifact-files.ts`
12
12
  * is the host adapter that executes these documents and plans.
@@ -57,10 +57,12 @@ declare function artifactDocument(input: {
57
57
  declare function isToolArtifactDocument(value: unknown): value is ToolArtifactDocument;
58
58
  declare function toolboxIndexDocument(tools: Record<string, unknown>, toolActions: Record<string, unknown>): ToolboxIndexDocument;
59
59
  declare function catalogIndexDocument(catalog: Pick<Catalog, 'tools' | 'actions'>): ToolboxIndexDocument;
60
+ declare function portableRecordSemantic(value: ToolRecord | ActionRecord): string;
61
+ declare function preserveProjectionTime<T extends ToolRecord | ActionRecord>(candidate: T, previous: unknown): T;
60
62
  /** The migration of one legacy aggregate `toolbox.json` catalog, as a pure
61
63
  * plan: every user tool becomes a per-tool artifact write, the whole legacy
62
64
  * catalog becomes the index, and the aggregate file is renamed out of the
63
65
  * way only after each record has a per-tool replacement. */
64
66
  declare function legacyMigrationPlan(legacy: unknown): LegacyMigrationPlan;
65
- export { LEGACY_TOOLBOX_BACKUP_FILE_NAME, LEGACY_TOOLBOX_FILE_NAME, TOOL_ARTIFACT_KIND, TOOL_ARTIFACT_SCHEMA_VERSION, TOOLBOX_INDEX_FILE_NAME, artifactDocument, catalogIndexDocument, isToolArtifactDocument, legacyMigrationPlan, safeToolId, toolboxIndexDocument, userArtifactFileName, };
67
+ export { LEGACY_TOOLBOX_BACKUP_FILE_NAME, LEGACY_TOOLBOX_FILE_NAME, TOOL_ARTIFACT_KIND, TOOL_ARTIFACT_SCHEMA_VERSION, TOOLBOX_INDEX_FILE_NAME, artifactDocument, catalogIndexDocument, isToolArtifactDocument, legacyMigrationPlan, safeToolId, portableRecordSemantic, preserveProjectionTime, toolboxIndexDocument, userArtifactFileName, };
66
68
  export type { ArtifactFileWrite, LegacyMigrationPlan, ToolArtifactDocument, ToolboxIndexDocument };
package/dist/artifacts.js CHANGED
@@ -1,11 +1,11 @@
1
1
  /**
2
2
  * Tool artifact format laws — the portable representation of a tool.
3
3
  *
4
- * One tool is one artifact file: the tool definition and every action it
5
- * owns travel together, and a file never carries a second tool. Artifact
6
- * files are the portable definition; the Toolbox database and
7
- * `toolbox.index.json` are derived caches. The format is ported byte-exact
8
- * from Engine `runtime/scripts/amalgm-mcp/toolbox/artifacts.js`.
4
+ * One compatibility artifact projects one current tool and every action it
5
+ * owns together; a file never carries a second tool. Immutable deployment
6
+ * documents are the portable source of truth. These artifacts, the Toolbox
7
+ * database, and `toolbox.index.json` are derived views retained for current
8
+ * Engine/UI readers.
9
9
  *
10
10
  * Pure laws only: nothing here touches the filesystem. `artifact-files.ts`
11
11
  * is the host adapter that executes these documents and plans.
@@ -81,6 +81,19 @@ function toolboxIndexDocument(tools, toolActions) {
81
81
  function catalogIndexDocument(catalog) {
82
82
  return toolboxIndexDocument(Object.fromEntries(catalog.tools.map((tool) => [tool.id, tool])), Object.fromEntries(catalog.actions.map((action) => [action.id, action])));
83
83
  }
84
+ function portableRecordSemantic(value) {
85
+ const { createdAt, updatedAt, ...portable } = value;
86
+ return JSON.stringify(portable);
87
+ }
88
+ function preserveProjectionTime(candidate, previous) {
89
+ if (!previous || typeof previous !== 'object')
90
+ return candidate;
91
+ const record = previous;
92
+ if (typeof record.createdAt !== 'string' || typeof record.updatedAt !== 'string'
93
+ || portableRecordSemantic(record) !== portableRecordSemantic(candidate))
94
+ return candidate;
95
+ return { ...candidate, createdAt: record.createdAt, updatedAt: record.updatedAt };
96
+ }
84
97
  /** The migration of one legacy aggregate `toolbox.json` catalog, as a pure
85
98
  * plan: every user tool becomes a per-tool artifact write, the whole legacy
86
99
  * catalog becomes the index, and the aggregate file is renamed out of the
@@ -109,4 +122,4 @@ function legacyMigrationPlan(legacy) {
109
122
  rename: { from: LEGACY_TOOLBOX_FILE_NAME, to: LEGACY_TOOLBOX_BACKUP_FILE_NAME },
110
123
  };
111
124
  }
112
- export { LEGACY_TOOLBOX_BACKUP_FILE_NAME, LEGACY_TOOLBOX_FILE_NAME, TOOL_ARTIFACT_KIND, TOOL_ARTIFACT_SCHEMA_VERSION, TOOLBOX_INDEX_FILE_NAME, artifactDocument, catalogIndexDocument, isToolArtifactDocument, legacyMigrationPlan, safeToolId, toolboxIndexDocument, userArtifactFileName, };
125
+ export { LEGACY_TOOLBOX_BACKUP_FILE_NAME, LEGACY_TOOLBOX_FILE_NAME, TOOL_ARTIFACT_KIND, TOOL_ARTIFACT_SCHEMA_VERSION, TOOLBOX_INDEX_FILE_NAME, artifactDocument, catalogIndexDocument, isToolArtifactDocument, legacyMigrationPlan, safeToolId, portableRecordSemantic, preserveProjectionTime, toolboxIndexDocument, userArtifactFileName, };
@@ -32,6 +32,15 @@ function refs(value, label) {
32
32
  result[string(key, label)] = string(reference, `${label}.${key}`);
33
33
  return result;
34
34
  }
35
+ function hostRoute(value) {
36
+ if (value === undefined)
37
+ return undefined;
38
+ const route = string(value, 'source.route');
39
+ if (!route.startsWith('/') || route.startsWith('//') || route.includes('?') || route.includes('#')) {
40
+ throw new Error('source.route must be an absolute path without query or fragment');
41
+ }
42
+ return route.replace(/\/+$/, '') || '/';
43
+ }
35
44
  function base(source) {
36
45
  return {
37
46
  timeoutMs: positive(source.timeoutMs, DEFAULT_TIMEOUT, 'source.timeoutMs'),
@@ -91,6 +100,7 @@ function normalizeSource(source) {
91
100
  ...(strings(source.args, 'source.args') ? { args: strings(source.args, 'source.args') } : {}),
92
101
  ...(source.cwd ? { cwd: string(source.cwd, 'source.cwd') } : {}),
93
102
  ...(source.serverName ? { serverName: string(source.serverName, 'source.serverName') } : {}),
103
+ ...(hostRoute(source.route) ? { route: hostRoute(source.route) } : {}),
94
104
  ...(refs(source.secretHeaders, 'source.secretHeaders') ? { secretHeaders: refs(source.secretHeaders, 'source.secretHeaders') } : {}),
95
105
  ...(refs(source.secretEnv, 'source.secretEnv') ? { secretEnv: refs(source.secretEnv, 'source.secretEnv') } : {}),
96
106
  };
@@ -0,0 +1,10 @@
1
+ import type { ToolDeployment } from './types.js';
2
+ /** Host effect for the portable, immutable deployment document tree. */
3
+ declare class DeploymentFiles {
4
+ private readonly root;
5
+ constructor(root: string);
6
+ file(deployment: ToolDeployment): string;
7
+ write(deployment: ToolDeployment): string;
8
+ materialize(deployments: readonly ToolDeployment[]): void;
9
+ }
10
+ export { DeploymentFiles };
@@ -0,0 +1,38 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { canonicalJson } from './deployments.js';
4
+ /** Host effect for the portable, immutable deployment document tree. */
5
+ class DeploymentFiles {
6
+ root;
7
+ constructor(root) {
8
+ this.root = root;
9
+ }
10
+ file(deployment) {
11
+ return path.join(this.root, deployment.subjectId, 'deployments', `${deployment.id}.json`);
12
+ }
13
+ write(deployment) {
14
+ const target = this.file(deployment);
15
+ const bytes = `${JSON.stringify(deployment, null, 2)}\n`;
16
+ try {
17
+ const existing = fs.readFileSync(target, 'utf8');
18
+ if (canonicalJson(JSON.parse(existing)) !== canonicalJson(deployment)) {
19
+ throw new Error(`Deployment file is immutable: ${deployment.id}`);
20
+ }
21
+ return target;
22
+ }
23
+ catch (error) {
24
+ if (error.code !== 'ENOENT')
25
+ throw error;
26
+ }
27
+ fs.mkdirSync(path.dirname(target), { recursive: true });
28
+ const temporary = `${target}.tmp`;
29
+ fs.writeFileSync(temporary, bytes, { flag: 'wx' });
30
+ fs.renameSync(temporary, target);
31
+ return target;
32
+ }
33
+ materialize(deployments) {
34
+ for (const deployment of deployments)
35
+ this.write(deployment);
36
+ }
37
+ }
38
+ export { DeploymentFiles };
@@ -0,0 +1,32 @@
1
+ import type { ApplyResult } from './types.js';
2
+ interface ToolDeployment {
3
+ schemaVersion: 1;
4
+ kind: 'amalgm-tool-deployment';
5
+ id: string;
6
+ /** The stable tool id, named generically to match @amalgm/live. */
7
+ subjectId: string;
8
+ previousDeploymentId: string | null;
9
+ definition: ApplyResult | null;
10
+ contentHash: string;
11
+ createdAt: string;
12
+ }
13
+ interface ToolDeploymentActivation {
14
+ type: 'deployment.activate';
15
+ deployment: ToolDeployment;
16
+ }
17
+ interface ToolDeploymentSnapshot {
18
+ version: 1;
19
+ deployments: Record<string, ToolDeployment>;
20
+ heads: Record<string, string>;
21
+ }
22
+ interface ToolDeploymentSurface {
23
+ readonly contract: 'amalgm.tools.deployments@1';
24
+ observeEdits(emit: (operation: ToolDeploymentActivation) => void): () => void;
25
+ applyRemote(operation: ToolDeploymentActivation, context: {
26
+ readonly hydrating: boolean;
27
+ }): void | Promise<void>;
28
+ applySnapshot(snapshot: ToolDeploymentSnapshot, context: {
29
+ readonly reason: 'hydration' | 'recovery';
30
+ }): void | Promise<void>;
31
+ }
32
+ export type { ToolDeployment, ToolDeploymentActivation, ToolDeploymentSnapshot, ToolDeploymentSurface, };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,19 @@
1
+ import type { ActionRecord, ApplyResult, ToolDeploymentActivation, ToolDeploymentSnapshot, ToolRecord } from './types.js';
2
+ declare const TOOL_DEPLOYMENT_CONTRACT: "amalgm.tools.deployments@1";
3
+ declare const TOOL_DEPLOYMENT_KIND: "amalgm-tool-deployment";
4
+ declare const TOOL_DEPLOYMENT_SCHEMA_VERSION: 1;
5
+ declare function canonicalJson(value: unknown): string;
6
+ declare function createToolDeployment(input: {
7
+ toolId: string;
8
+ previousDeploymentId: string | null;
9
+ definition: ApplyResult | null;
10
+ createdAt: string;
11
+ }): ToolDeploymentActivation;
12
+ declare function assertToolDeploymentActivation(value: unknown): asserts value is ToolDeploymentActivation;
13
+ declare function deploymentRevisionId(input: {
14
+ heads: Readonly<Record<string, string>>;
15
+ systemTools?: readonly ToolRecord[];
16
+ systemActions?: readonly ActionRecord[];
17
+ }): string;
18
+ declare function emptyToolDeploymentSnapshot(): ToolDeploymentSnapshot;
19
+ export { TOOL_DEPLOYMENT_CONTRACT, TOOL_DEPLOYMENT_KIND, TOOL_DEPLOYMENT_SCHEMA_VERSION, assertToolDeploymentActivation, canonicalJson, createToolDeployment, deploymentRevisionId, emptyToolDeploymentSnapshot, };
@@ -0,0 +1,98 @@
1
+ import { createHash } from 'node:crypto';
2
+ const TOOL_DEPLOYMENT_CONTRACT = 'amalgm.tools.deployments@1';
3
+ const TOOL_DEPLOYMENT_KIND = 'amalgm-tool-deployment';
4
+ const TOOL_DEPLOYMENT_SCHEMA_VERSION = 1;
5
+ function canonical(value) {
6
+ if (Array.isArray(value))
7
+ return value.map(canonical);
8
+ if (!value || typeof value !== 'object')
9
+ return value;
10
+ return Object.fromEntries(Object.entries(value)
11
+ .filter(([, item]) => item !== undefined)
12
+ .sort(([left], [right]) => left.localeCompare(right))
13
+ .map(([key, item]) => [key, canonical(item)]));
14
+ }
15
+ function canonicalJson(value) {
16
+ return JSON.stringify(canonical(value));
17
+ }
18
+ function sha256(value) {
19
+ return createHash('sha256').update(canonicalJson(value)).digest('hex');
20
+ }
21
+ function createToolDeployment(input) {
22
+ const contentHash = sha256(input.definition);
23
+ const identity = sha256({
24
+ subjectId: input.toolId,
25
+ previousDeploymentId: input.previousDeploymentId,
26
+ contentHash,
27
+ createdAt: input.createdAt,
28
+ });
29
+ return Object.freeze({
30
+ type: 'deployment.activate',
31
+ deployment: Object.freeze({
32
+ schemaVersion: TOOL_DEPLOYMENT_SCHEMA_VERSION,
33
+ kind: TOOL_DEPLOYMENT_KIND,
34
+ id: `tooldep_${identity}`,
35
+ subjectId: input.toolId,
36
+ previousDeploymentId: input.previousDeploymentId,
37
+ definition: input.definition,
38
+ contentHash,
39
+ createdAt: input.createdAt,
40
+ }),
41
+ });
42
+ }
43
+ function assertRecord(value, label) {
44
+ if (!value || typeof value !== 'object' || Array.isArray(value))
45
+ throw new Error(`${label} must be an object`);
46
+ }
47
+ function assertToolDeploymentActivation(value) {
48
+ assertRecord(value, 'Tool deployment activation');
49
+ if (value.type !== 'deployment.activate')
50
+ throw new Error('Tool deployment operation must be deployment.activate');
51
+ assertRecord(value.deployment, 'Tool deployment');
52
+ const deployment = value.deployment;
53
+ if (deployment.schemaVersion !== TOOL_DEPLOYMENT_SCHEMA_VERSION || deployment.kind !== TOOL_DEPLOYMENT_KIND) {
54
+ throw new Error('Unsupported tool deployment document');
55
+ }
56
+ if (typeof deployment.id !== 'string' || !deployment.id
57
+ || typeof deployment.subjectId !== 'string' || !deployment.subjectId
58
+ || typeof deployment.createdAt !== 'string' || !deployment.createdAt
59
+ || (deployment.previousDeploymentId !== null && typeof deployment.previousDeploymentId !== 'string')) {
60
+ throw new Error('Tool deployment identity is incomplete');
61
+ }
62
+ if (deployment.definition !== null) {
63
+ assertRecord(deployment.definition, 'Tool deployment definition');
64
+ assertRecord(deployment.definition.tool, 'Tool deployment tool');
65
+ if (deployment.definition.tool.id !== deployment.subjectId) {
66
+ throw new Error('Tool deployment subject does not match its tool');
67
+ }
68
+ if (deployment.definition.tool.origin === 'system') {
69
+ throw new Error('System tools cannot arrive as user deployments');
70
+ }
71
+ if (!Array.isArray(deployment.definition.actions)
72
+ || deployment.definition.actions.some((action) => action.toolId !== deployment.subjectId)) {
73
+ throw new Error('Tool deployment actions must all belong to its subject');
74
+ }
75
+ }
76
+ if (deployment.contentHash !== sha256(deployment.definition)) {
77
+ throw new Error(`Tool deployment content hash is invalid: ${deployment.id}`);
78
+ }
79
+ const expected = createToolDeployment({
80
+ toolId: deployment.subjectId,
81
+ previousDeploymentId: deployment.previousDeploymentId,
82
+ definition: deployment.definition,
83
+ createdAt: deployment.createdAt,
84
+ }).deployment.id;
85
+ if (deployment.id !== expected)
86
+ throw new Error(`Tool deployment id is invalid: ${deployment.id}`);
87
+ }
88
+ function deploymentRevisionId(input) {
89
+ return `toolbox_${sha256({
90
+ heads: input.heads,
91
+ systemTools: input.systemTools || [],
92
+ systemActions: input.systemActions || [],
93
+ })}`;
94
+ }
95
+ function emptyToolDeploymentSnapshot() {
96
+ return { version: 1, deployments: {}, heads: {} };
97
+ }
98
+ export { TOOL_DEPLOYMENT_CONTRACT, TOOL_DEPLOYMENT_KIND, TOOL_DEPLOYMENT_SCHEMA_VERSION, assertToolDeploymentActivation, canonicalJson, createToolDeployment, deploymentRevisionId, emptyToolDeploymentSnapshot, };
@@ -0,0 +1,8 @@
1
+ import type { HostMcpToolDefinitionInput, ToolDefinition } from './types.js';
2
+ /**
3
+ * Project an owning SDK's MCP descriptors into one immutable first-party
4
+ * Toolbox tool. The descriptors remain authoritative; this adapter does not
5
+ * copy or reinterpret action schemas.
6
+ */
7
+ declare function defineHostMcpTool(input: HostMcpToolDefinitionInput): ToolDefinition;
8
+ export { defineHostMcpTool };
@@ -0,0 +1,40 @@
1
+ import { defineTool } from './definition.js';
2
+ const EMPTY_INPUT = {
3
+ type: 'object',
4
+ properties: {},
5
+ additionalProperties: false,
6
+ };
7
+ /**
8
+ * Project an owning SDK's MCP descriptors into one immutable first-party
9
+ * Toolbox tool. The descriptors remain authoritative; this adapter does not
10
+ * copy or reinterpret action schemas.
11
+ */
12
+ function defineHostMcpTool(input) {
13
+ const actions = input.tools.map((tool) => ({
14
+ name: tool.name,
15
+ ...(tool.description ? { description: tool.description } : {}),
16
+ inputSchema: tool.inputSchema || EMPTY_INPUT,
17
+ target: { name: tool.name },
18
+ }));
19
+ return defineTool({
20
+ id: input.id,
21
+ name: input.name,
22
+ ...(input.description ? { description: input.description } : {}),
23
+ owner: input.owner || 'amalgm',
24
+ origin: 'system',
25
+ source: {
26
+ type: 'mcp',
27
+ transport: 'host',
28
+ serverName: input.serverName,
29
+ route: input.route,
30
+ },
31
+ actions,
32
+ policy: { firstParty: true },
33
+ ...(input.display ? { display: structuredClone(input.display) } : {}),
34
+ metadata: {
35
+ platform: true,
36
+ ...(input.metadata ? structuredClone(input.metadata) : {}),
37
+ },
38
+ });
39
+ }
40
+ export { defineHostMcpTool };
package/dist/http.js CHANGED
@@ -16,7 +16,12 @@ function actionDocument(action) {
16
16
  return { ...action };
17
17
  }
18
18
  function catalogDocument(catalog) {
19
- return toolboxIndexDocument(Object.fromEntries(catalog.tools.map((tool) => [tool.id, toolDocument(tool)])), Object.fromEntries(catalog.actions.map((action) => [action.id, actionDocument(action)])));
19
+ return {
20
+ ...toolboxIndexDocument(Object.fromEntries(catalog.tools.map((tool) => [tool.id, toolDocument(tool)])), Object.fromEntries(catalog.actions.map((action) => [action.id, actionDocument(action)]))),
21
+ revision: catalog.revision,
22
+ revisionId: catalog.revisionId,
23
+ deployments: catalog.deployments,
24
+ };
20
25
  }
21
26
  async function readBody(req) {
22
27
  const chunks = [];
package/dist/index.d.ts CHANGED
@@ -2,10 +2,12 @@ export { ArtifactFiles } from './artifact-files.js';
2
2
  export { LEGACY_TOOLBOX_BACKUP_FILE_NAME, LEGACY_TOOLBOX_FILE_NAME, TOOL_ARTIFACT_KIND, TOOL_ARTIFACT_SCHEMA_VERSION, TOOLBOX_INDEX_FILE_NAME, artifactDocument, catalogIndexDocument, isToolArtifactDocument, legacyMigrationPlan, safeToolId, toolboxIndexDocument, userArtifactFileName, } from './artifacts.js';
3
3
  export type { ArtifactFileWrite, LegacyMigrationPlan, ToolArtifactDocument, ToolboxIndexDocument, } from './artifacts.js';
4
4
  export { defineTool, normalizeDefinition } from './definition.js';
5
+ export { defineHostMcpTool } from './host-mcp-tool.js';
6
+ export { TOOL_DEPLOYMENT_CONTRACT, TOOL_DEPLOYMENT_KIND, TOOL_DEPLOYMENT_SCHEMA_VERSION, assertToolDeploymentActivation, createToolDeployment, deploymentRevisionId, emptyToolDeploymentSnapshot, } from './deployments.js';
5
7
  export { catalogDocument, createToolboxHttpServer } from './http.js';
6
8
  export type { ToolboxHttpServer } from './http.js';
7
9
  export { actionId, actionName, id, mcpName } from './ids.js';
8
- export { actionTools, callMcpTool, createMcpTools, findMcpTool, managementTools, } from './mcp.js';
10
+ export { actionTools, callMcpTool, createMcpTools, findMcpTool, managementToolDescriptors, managementTools, } from './mcp.js';
9
11
  export { createMcpServer } from './mcp-server.js';
10
12
  export { Notifications, createNotificationsDriver, notificationToolDefinition, } from './notifications.js';
11
13
  export type { EmailDelivery, EmailDeliveryReceipt, EmailNotificationRequest, NotificationLevel, NotificationsOptions, } from './notifications.js';
package/dist/index.js CHANGED
@@ -1,9 +1,11 @@
1
1
  export { ArtifactFiles } from './artifact-files.js';
2
2
  export { LEGACY_TOOLBOX_BACKUP_FILE_NAME, LEGACY_TOOLBOX_FILE_NAME, TOOL_ARTIFACT_KIND, TOOL_ARTIFACT_SCHEMA_VERSION, TOOLBOX_INDEX_FILE_NAME, artifactDocument, catalogIndexDocument, isToolArtifactDocument, legacyMigrationPlan, safeToolId, toolboxIndexDocument, userArtifactFileName, } from './artifacts.js';
3
3
  export { defineTool, normalizeDefinition } from './definition.js';
4
+ export { defineHostMcpTool } from './host-mcp-tool.js';
5
+ export { TOOL_DEPLOYMENT_CONTRACT, TOOL_DEPLOYMENT_KIND, TOOL_DEPLOYMENT_SCHEMA_VERSION, assertToolDeploymentActivation, createToolDeployment, deploymentRevisionId, emptyToolDeploymentSnapshot, } from './deployments.js';
4
6
  export { catalogDocument, createToolboxHttpServer } from './http.js';
5
7
  export { actionId, actionName, id, mcpName } from './ids.js';
6
- export { actionTools, callMcpTool, createMcpTools, findMcpTool, managementTools, } from './mcp.js';
8
+ export { actionTools, callMcpTool, createMcpTools, findMcpTool, managementToolDescriptors, managementTools, } from './mcp.js';
7
9
  export { createMcpServer } from './mcp-server.js';
8
10
  export { Notifications, createNotificationsDriver, notificationToolDefinition, } from './notifications.js';
9
11
  export { createProxyEmailDelivery } from './proxy-email.js';
@@ -1,7 +1,7 @@
1
1
  import readline from 'node:readline';
2
2
  import type { Readable, Writable } from 'node:stream';
3
3
  import { Toolbox } from './toolbox.js';
4
- import type { ToolboxOptions } from './types.js';
4
+ import type { McpOptions, ToolboxOptions } from './types.js';
5
5
  interface Request {
6
6
  jsonrpc?: string;
7
7
  id?: string | number;
@@ -10,6 +10,7 @@ interface Request {
10
10
  }
11
11
  declare function createMcpServer(options?: ToolboxOptions & {
12
12
  toolbox?: Toolbox;
13
+ mcp?: McpOptions;
13
14
  }): {
14
15
  toolbox: Toolbox;
15
16
  handle: (request: Request) => Promise<unknown>;
@@ -7,6 +7,7 @@ function descriptor(tool) {
7
7
  }
8
8
  function createMcpServer(options = {}) {
9
9
  const toolbox = options.toolbox || new Toolbox(options);
10
+ const mcpOptions = options.mcp || {};
10
11
  async function handle(request) {
11
12
  if (request.method === 'initialize') {
12
13
  return {
@@ -17,12 +18,12 @@ function createMcpServer(options = {}) {
17
18
  }
18
19
  if (request.method === 'ping')
19
20
  return {};
20
- const tools = createMcpTools(toolbox);
21
+ const tools = createMcpTools(toolbox, mcpOptions);
21
22
  if (request.method === 'tools/list')
22
23
  return { tools: tools.map(descriptor) };
23
24
  if (request.method === 'tools/call') {
24
25
  try {
25
- return await callMcpTool(toolbox, String(request.params?.name || ''), request.params?.arguments || {});
26
+ return await callMcpTool(toolbox, String(request.params?.name || ''), request.params?.arguments || {}, mcpOptions);
26
27
  }
27
28
  catch (error) {
28
29
  if (error instanceof Error && error.message.startsWith('Unknown tool:')) {