@amalgm/tools 0.1.7-preview.34746901886 → 0.1.7-preview.34938534039

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 (47) hide show
  1. package/PURPOSE.md +29 -1
  2. package/README.md +29 -5
  3. package/dist/api-driver.d.ts +2 -1
  4. package/dist/api-driver.js +67 -48
  5. package/dist/cli-driver.js +2 -1
  6. package/dist/commands.js +3 -2
  7. package/dist/connection-auth.d.ts +11 -0
  8. package/dist/connection-auth.js +98 -0
  9. package/dist/connection-source.d.ts +23 -0
  10. package/dist/connection-source.js +62 -0
  11. package/dist/connection-types.d.ts +34 -0
  12. package/dist/connection-types.js +1 -0
  13. package/dist/connections.d.ts +14 -0
  14. package/dist/connections.js +98 -0
  15. package/dist/credential-operations.d.ts +7 -0
  16. package/dist/credential-operations.js +37 -0
  17. package/dist/definition.js +10 -3
  18. package/dist/http-mutations.d.ts +63 -0
  19. package/dist/http-mutations.js +41 -0
  20. package/dist/http.d.ts +2 -3
  21. package/dist/http.js +9 -3
  22. package/dist/index.d.ts +5 -0
  23. package/dist/index.js +2 -0
  24. package/dist/input.js +7 -32
  25. package/dist/loadout.d.ts +3 -0
  26. package/dist/loadout.js +23 -0
  27. package/dist/mcp-driver.d.ts +16 -0
  28. package/dist/mcp-driver.js +44 -0
  29. package/dist/mcp-search.d.ts +8 -0
  30. package/dist/mcp-search.js +51 -0
  31. package/dist/mcp-types.d.ts +13 -0
  32. package/dist/mcp-types.js +1 -0
  33. package/dist/mcp.js +23 -19
  34. package/dist/oauth.d.ts +29 -0
  35. package/dist/oauth.js +131 -0
  36. package/dist/prepared-catalog.d.ts +3 -1
  37. package/dist/prepared-catalog.js +20 -1
  38. package/dist/results.d.ts +4 -1
  39. package/dist/results.js +21 -16
  40. package/dist/selection.js +3 -0
  41. package/dist/toolbox-view.d.ts +4 -1
  42. package/dist/toolbox-view.js +8 -2
  43. package/dist/toolbox.d.ts +7 -0
  44. package/dist/toolbox.js +25 -14
  45. package/dist/types.d.ts +27 -20
  46. package/docs/SHELL_INTEGRATION.md +8 -3
  47. package/package.json +5 -4
package/dist/oauth.js ADDED
@@ -0,0 +1,131 @@
1
+ import { credentialOperations } from './credential-operations.js';
2
+ import { randomBytes } from 'node:crypto';
3
+ import { auth, selectClientAuthMethod } from '@modelcontextprotocol/sdk/client/auth.js';
4
+ import { connectionSource } from './connection-source.js';
5
+ export const authorizationReference = (toolId) => `tools:${toolId}:oauth-pending`;
6
+ /** MCP's OAuth flow, with all pending and granted secrets in the host vault. */
7
+ export class ToolAuthorization {
8
+ store;
9
+ connect;
10
+ #completing = new Set();
11
+ constructor(store, connect) {
12
+ this.store = store;
13
+ this.connect = connect;
14
+ this.store = store && credentialOperations(store);
15
+ }
16
+ async begin(input) {
17
+ if (!this.store)
18
+ throw new Error('Tool credential vault is unavailable');
19
+ const { definition } = connectionSource({ definition: input.definition });
20
+ if (definition.source.type !== 'mcp' || !definition.source.url)
21
+ throw new Error('OAuth requires a remote MCP source');
22
+ const redirect = new URL(input.redirectUri);
23
+ if (!['http:', 'https:'].includes(redirect.protocol) || redirect.username || redirect.password || redirect.hash) {
24
+ throw new Error('Invalid OAuth callback URL');
25
+ }
26
+ const state = `${Buffer.from(definition.id).toString('base64url')}.${randomBytes(32).toString('base64url')}`;
27
+ const pending = {
28
+ input: { ...input, definition }, state, expiresAt: Date.now() + 10 * 60_000,
29
+ ...(input.clientId ? { client: { client_id: input.clientId, ...(input.clientSecret ? { client_secret: input.clientSecret } : {}) } } : {}),
30
+ ...(input.metadata ? { discovery: {
31
+ authorizationServerUrl: input.metadata.issuer,
32
+ authorizationServerMetadata: input.metadata,
33
+ } } : {}),
34
+ };
35
+ const reference = authorizationReference(definition.id);
36
+ // Publish the attempt before network work so later attempts/disconnect win.
37
+ const marker = JSON.stringify(pending);
38
+ await this.store.set(reference, marker);
39
+ try {
40
+ const { provider, authorizationUrl } = oauthProvider(pending);
41
+ const result = await auth(provider, { serverUrl: definition.source.url, scope: input.scope, fetchFn: oauthFetch });
42
+ if (result !== 'REDIRECT' || !authorizationUrl())
43
+ throw new Error('OAuth did not return an authorization URL');
44
+ if (!await credentialOperations(this.store).replace(reference, marker, JSON.stringify(pending))) {
45
+ throw new Error('Tool authorization was cancelled');
46
+ }
47
+ return { url: authorizationUrl(), state, toolId: definition.id };
48
+ }
49
+ catch (error) {
50
+ await credentialOperations(this.store).replace(reference, marker, undefined);
51
+ throw error;
52
+ }
53
+ }
54
+ async complete(input) {
55
+ if (!this.store || !input.state || !input.code)
56
+ throw new Error('OAuth state and code are required');
57
+ if (this.#completing.has(input.state))
58
+ throw new Error('OAuth callback is already being consumed');
59
+ const toolId = Buffer.from(input.state.split('.')[0] || '', 'base64url').toString();
60
+ const reference = authorizationReference(toolId);
61
+ const encoded = await this.store.get(reference);
62
+ if (!encoded)
63
+ throw new Error('Tool authorization expired or was cancelled');
64
+ const pending = JSON.parse(encoded);
65
+ if (pending.state !== input.state || pending.expiresAt < Date.now())
66
+ throw new Error('Tool authorization expired or is invalid');
67
+ if (this.#completing.has(input.state))
68
+ throw new Error('OAuth callback is already being consumed');
69
+ this.#completing.add(input.state);
70
+ try {
71
+ const { provider } = oauthProvider(pending);
72
+ const source = pending.input.definition.source;
73
+ if (source.type !== 'mcp' || !source.url)
74
+ throw new Error('OAuth source is missing');
75
+ const result = await auth(provider, { serverUrl: source.url, authorizationCode: input.code, fetchFn: oauthFetch });
76
+ const tokens = pending.tokens;
77
+ const client = pending.client;
78
+ const metadata = pending.discovery?.authorizationServerMetadata;
79
+ if (result !== 'AUTHORIZED' || !tokens || !client || !metadata?.token_endpoint)
80
+ throw new Error('OAuth returned incomplete credentials');
81
+ if (tokens.token_type.toLowerCase() !== 'bearer')
82
+ throw new Error('Unsupported OAuth token type');
83
+ return await this.connect({
84
+ definition: pending.input.definition,
85
+ credentials: { oauth: {
86
+ type: 'oauth', accessToken: tokens.access_token, refreshToken: tokens.refresh_token,
87
+ clientId: client.client_id, clientSecret: client.client_secret,
88
+ tokenUrl: metadata.token_endpoint, scope: tokens.scope || pending.input.scope,
89
+ tokenEndpointAuthMethod: selectClientAuthMethod(client, metadata.token_endpoint_auth_methods_supported || ['client_secret_post']),
90
+ ...(tokens.expires_in ? { expiresAt: new Date(Date.now() + tokens.expires_in * 1000).toISOString() } : {}),
91
+ } },
92
+ }, async () => {
93
+ if (await this.store.get(reference) !== encoded)
94
+ throw new Error('Tool authorization changed or was cancelled');
95
+ });
96
+ }
97
+ finally {
98
+ this.#completing.delete(input.state);
99
+ await credentialOperations(this.store).replace(reference, encoded, undefined);
100
+ }
101
+ }
102
+ }
103
+ function oauthProvider(pending) {
104
+ let url;
105
+ const provider = {
106
+ redirectUrl: pending.input.redirectUri,
107
+ clientMetadata: {
108
+ client_name: 'Amalgm', redirect_uris: [pending.input.redirectUri],
109
+ grant_types: ['authorization_code', 'refresh_token'], response_types: ['code'],
110
+ token_endpoint_auth_method: pending.input.clientSecret ? 'client_secret_post' : 'none',
111
+ },
112
+ state: () => pending.state,
113
+ clientInformation: () => pending.client,
114
+ saveClientInformation: (client) => { pending.client = client; },
115
+ tokens: () => pending.tokens,
116
+ saveTokens: (tokens) => { pending.tokens = tokens; },
117
+ discoveryState: () => pending.discovery,
118
+ saveDiscoveryState: (discovery) => { pending.discovery = discovery; },
119
+ saveCodeVerifier: (verifier) => { pending.verifier = verifier; },
120
+ codeVerifier: () => { if (!pending.verifier)
121
+ throw new Error('OAuth verifier is missing'); return pending.verifier; },
122
+ redirectToAuthorization: (target) => { url = target.toString(); },
123
+ };
124
+ return { provider, authorizationUrl: () => url };
125
+ }
126
+ const oauthFetch = async (input, init) => {
127
+ const response = await fetch(input, { ...init, redirect: 'manual', signal: AbortSignal.timeout(15_000) });
128
+ if (response.status >= 300 && response.status < 400)
129
+ throw new Error('OAuth refused a redirect');
130
+ return response;
131
+ };
@@ -1,3 +1,5 @@
1
- import type { Catalog, LoadoutInput } from './types.js';
1
+ import { ToolboxView } from './toolbox-view.js';
2
+ import type { CallOptions, Catalog, LoadoutInput, ToolDriver } from './types.js';
2
3
  /** Capture exact definitions; a caller cannot expand a prepared loadout later. */
3
4
  export declare function preparedCatalog(catalog: Catalog, revisionId: string, loadout: LoadoutInput): Catalog;
5
+ export declare function preparedView(read: () => Catalog, revisionId: string, input: LoadoutInput, drivers: ReadonlyMap<string, ToolDriver>, defaults: CallOptions): ToolboxView;
@@ -1,10 +1,18 @@
1
1
  import { selected } from './selection.js';
2
+ import { normalizeLoadout } from './loadout.js';
3
+ import { ToolboxView } from './toolbox-view.js';
2
4
  /** Capture exact definitions; a caller cannot expand a prepared loadout later. */
3
5
  export function preparedCatalog(catalog, revisionId, loadout) {
4
6
  if (catalog.revisionId !== revisionId) {
5
7
  throw new Error(`Toolbox deployment revision changed: expected ${revisionId}, current ${catalog.revisionId}`);
6
8
  }
7
- const ids = new Set(Array.isArray(loadout) ? loadout : loadout.toolIds);
9
+ loadout = normalizeLoadout(loadout);
10
+ const ids = new Set(loadout.toolIds);
11
+ for (const id of Object.keys(loadout.exposure || {})) {
12
+ if (!catalog.tools.some((tool) => tool.id === id) && !catalog.actions.some((action) => action.id === id)) {
13
+ throw new Error(`Exposure refers to an unknown tool or action: ${id}`);
14
+ }
15
+ }
8
16
  for (const id of ids) {
9
17
  const action = catalog.actions.find((item) => item.id === id);
10
18
  const tool = catalog.tools.find((item) => item.id === (action?.toolId || id));
@@ -23,3 +31,14 @@ export function preparedCatalog(catalog, revisionId, loadout) {
23
31
  actions,
24
32
  });
25
33
  }
34
+ export function preparedView(read, revisionId, input, drivers, defaults) {
35
+ const loadout = normalizeLoadout(input);
36
+ const captured = preparedCatalog(read(), revisionId, loadout);
37
+ return new ToolboxView(() => {
38
+ const active = new Set(read().tools.filter((tool) => tool.status === 'enabled').map((tool) => tool.id));
39
+ return structuredClone({ ...captured,
40
+ tools: captured.tools.filter((tool) => active.has(tool.id)),
41
+ actions: captured.actions.filter((action) => active.has(action.toolId)),
42
+ });
43
+ }, new Map(drivers), defaults, structuredClone(loadout));
44
+ }
package/dist/results.d.ts CHANGED
@@ -1,6 +1,9 @@
1
1
  import type { ToolResult } from './types.js';
2
2
  declare function textResult(value: unknown): ToolResult;
3
3
  declare function structuredResult(value: unknown): ToolResult;
4
+ /** The inverse of `structuredResult`'s envelope: a value that is not a plain
5
+ * object is carried as `{ result: value }`, and this returns it unchanged. */
6
+ declare function structuredValue(structuredContent: ToolResult['structuredContent']): unknown;
4
7
  declare function errorResult(value: unknown): ToolResult;
5
8
  declare function boundedResult(result: ToolResult, maximum: number): ToolResult;
6
- export { boundedResult, errorResult, structuredResult, textResult };
9
+ export { boundedResult, errorResult, structuredResult, structuredValue, textResult };
package/dist/results.js CHANGED
@@ -3,25 +3,30 @@ function textResult(value) {
3
3
  return { content: [{ type: 'text', text }] };
4
4
  }
5
5
  function structuredResult(value) {
6
- return { ...textResult(value), structuredContent: value };
6
+ const structuredContent = value && typeof value === 'object' && !Array.isArray(value)
7
+ ? value : { result: value ?? null };
8
+ return { ...textResult(value), structuredContent };
9
+ }
10
+ /** The inverse of `structuredResult`'s envelope: a value that is not a plain
11
+ * object is carried as `{ result: value }`, and this returns it unchanged. */
12
+ function structuredValue(structuredContent) {
13
+ return structuredContent
14
+ && Object.keys(structuredContent).length === 1
15
+ && 'result' in structuredContent
16
+ ? structuredContent.result : structuredContent;
7
17
  }
8
18
  function errorResult(value) {
9
19
  return { ...textResult(value instanceof Error ? value.message : value), isError: true };
10
20
  }
11
21
  function boundedResult(result, maximum) {
12
- let remaining = Math.max(0, maximum);
13
- let truncated = false;
14
- const content = result.content.map((item) => {
15
- const bytes = Buffer.from(item.text);
16
- if (bytes.length <= remaining) {
17
- remaining -= bytes.length;
18
- return item;
19
- }
20
- truncated = true;
21
- const text = bytes.subarray(0, remaining).toString('utf8');
22
- remaining = 0;
23
- return { ...item, text: `${text}\n[output truncated]` };
24
- });
25
- return { ...result, content, ...(truncated ? { truncated: true } : {}) };
22
+ const bytes = Buffer.from(JSON.stringify(result));
23
+ if (bytes.length <= maximum)
24
+ return result;
25
+ const text = result.content.map((item) => item.type === 'text' ? item.text : JSON.stringify(item)).join('\n');
26
+ const marker = '\n[output truncated]';
27
+ return {
28
+ ...textResult(Buffer.from(text).subarray(0, Math.max(0, maximum - Buffer.byteLength(marker))).toString('utf8') + marker),
29
+ ...(result.isError ? { isError: true } : {}), truncated: true,
30
+ };
26
31
  }
27
- export { boundedResult, errorResult, structuredResult, textResult };
32
+ export { boundedResult, errorResult, structuredResult, structuredValue, textResult };
package/dist/selection.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { actionExposure } from './loadout.js';
1
2
  function selected(catalog, loadout) {
2
3
  const ids = loadout === undefined
3
4
  ? null
@@ -9,6 +10,8 @@ function selected(catalog, loadout) {
9
10
  return [];
10
11
  if (ids && !ids.has(tool.id) && !ids.has(action.id))
11
12
  return [];
13
+ if (actionExposure(loadout, tool.id, action.id) === 'hidden')
14
+ return [];
12
15
  return [{ tool, action }];
13
16
  });
14
17
  }
@@ -2,8 +2,11 @@ import type { ActionRecord, ApplyResult, CallOptions, Catalog, LoadoutInput, Too
2
2
  declare class ToolboxView {
3
3
  private readonly readCatalog;
4
4
  private readonly drivers;
5
- constructor(readCatalog: () => Catalog, drivers: ReadonlyMap<string, ToolDriver>);
5
+ private readonly defaults;
6
+ private readonly loadout?;
7
+ constructor(readCatalog: () => Catalog, drivers: ReadonlyMap<string, ToolDriver>, defaults?: CallOptions, loadout?: LoadoutInput | undefined);
6
8
  catalog(): Catalog;
9
+ exposure(action: ActionRecord): import("./types.js").ToolExposure;
7
10
  list(loadout?: LoadoutInput): Array<{
8
11
  tool: ToolRecord;
9
12
  actions: ActionRecord[];
@@ -1,15 +1,21 @@
1
1
  import { id, mcpName } from './ids.js';
2
+ import { actionExposure } from './loadout.js';
2
3
  import { validateInput } from './input.js';
3
4
  import { callableActions, queryTools, resolveAction, resolveCallableAction } from './query.js';
4
5
  import { findSelected, selected } from './selection.js';
5
6
  class ToolboxView {
6
7
  readCatalog;
7
8
  drivers;
8
- constructor(readCatalog, drivers) {
9
+ defaults;
10
+ loadout;
11
+ constructor(readCatalog, drivers, defaults = {}, loadout) {
9
12
  this.readCatalog = readCatalog;
10
13
  this.drivers = drivers;
14
+ this.defaults = defaults;
15
+ this.loadout = loadout;
11
16
  }
12
17
  catalog() { return this.readCatalog(); }
18
+ exposure(action) { return actionExposure(this.loadout, action.toolId, action.id); }
13
19
  list(loadout) {
14
20
  const catalog = this.catalog();
15
21
  const runnable = selected(catalog, loadout);
@@ -58,7 +64,7 @@ class ToolboxView {
58
64
  const driver = this.driverFor(resolved.tool);
59
65
  if (!driver)
60
66
  throw new Error(`No ${resolved.tool.source.type} driver is configured for ${resolved.tool.id}`);
61
- return driver.call({ ...resolved, input: validateInput(resolved.action.inputSchema, input), options });
67
+ return driver.call({ ...resolved, input: validateInput(resolved.action.inputSchema, input), options: { ...this.defaults, ...options } });
62
68
  }
63
69
  hasDriver(tool) { return this.driverFor(tool) !== null; }
64
70
  async callMcp(name, input = {}, options = {}) {
package/dist/toolbox.d.ts CHANGED
@@ -1,12 +1,17 @@
1
+ import { ToolAuthorization } from './oauth.js';
2
+ import type { ConnectToolInput } from './connection-types.js';
1
3
  import { ToolboxView } from './toolbox-view.js';
2
4
  import type { ActionDefinition, ActionPatch, ActionRecord, ApplyResult, CallOptions, Catalog, LoadoutInput, ToolDefinition, ToolboxOptions, ToolDeployment, ToolDeploymentActivation, ToolDeploymentSnapshot, ToolDeploymentSurface, ToolPatch, ToolQuery, ToolRecord, ToolResult } from './types.js';
3
5
  declare class Toolbox {
6
+ readonly authorization: ToolAuthorization;
4
7
  private readonly store;
5
8
  private readonly deploymentService;
6
9
  private readonly projection;
7
10
  private readonly system;
8
11
  private readonly drivers;
9
12
  private readonly view;
13
+ private readonly connectionService;
14
+ private readonly authentication;
10
15
  constructor(options?: ToolboxOptions);
11
16
  catalog(): Catalog;
12
17
  list(loadout?: LoadoutInput): Array<{
@@ -15,6 +20,8 @@ declare class Toolbox {
15
20
  }>;
16
21
  /** Pin one exact deployment revision and loadout for an execution. */
17
22
  prepare(revisionId: string, loadout: LoadoutInput): ToolboxView;
23
+ connect(input: ConnectToolInput): Promise<ApplyResult>;
24
+ disconnect(toolId: string): Promise<ApplyResult>;
18
25
  query(filters?: ToolQuery): {
19
26
  tool: ToolRecord;
20
27
  actions: ActionRecord[];
package/dist/toolbox.js CHANGED
@@ -1,6 +1,9 @@
1
1
  import path from 'node:path';
2
2
  import { defaultDatabase } from './toolbox-state-dir.js';
3
- import { apiDriver } from './api-driver.js';
3
+ import { apiDriver, graphqlDriver } from './api-driver.js';
4
+ import { ToolAuthentication } from './connection-auth.js';
5
+ import { ToolConnections } from './connections.js';
6
+ import { ToolAuthorization } from './oauth.js';
4
7
  import { applyDefinition } from './apply-definition.js';
5
8
  import { ArtifactFiles } from './artifact-files.js';
6
9
  import { preserveProjectionTime } from './artifacts.js';
@@ -8,7 +11,7 @@ import { createCliDriver } from './cli-driver.js';
8
11
  import { DeploymentFiles } from './deployment-files.js';
9
12
  import { deploymentRevisionId } from './deployments.js';
10
13
  import { normalizeDefinition } from './definition.js';
11
- import { preparedCatalog } from './prepared-catalog.js';
14
+ import { preparedView } from './prepared-catalog.js';
12
15
  import { assertMcpNamesUnique, id } from './ids.js';
13
16
  import { Store } from './store.js';
14
17
  import { ToolboxDeployments } from './toolbox-deployments.js';
@@ -16,20 +19,26 @@ import { ToolboxProjection } from './toolbox-projection.js';
16
19
  import { ToolboxView } from './toolbox-view.js';
17
20
  import { linkTool, removeAction, updateAction, updateTool, upsertAction } from './updates.js';
18
21
  class Toolbox {
22
+ authorization;
19
23
  store;
20
24
  deploymentService;
21
25
  projection;
22
26
  system;
23
27
  drivers = new Map();
24
28
  view;
29
+ connectionService;
30
+ authentication;
25
31
  constructor(options = {}) {
26
32
  const databaseFile = defaultDatabase(options);
27
33
  this.store = new Store(databaseFile);
28
34
  const artifacts = new ArtifactFiles(path.dirname(databaseFile));
29
35
  const deploymentFiles = new DeploymentFiles(path.resolve(options.deploymentDir || options.stateDir || path.dirname(databaseFile)));
30
36
  const priorIndex = artifacts.readIndex();
31
- for (const driver of [createCliDriver(options.environment), apiDriver, ...(options.drivers || [])])
37
+ for (const driver of [createCliDriver(options.environment), apiDriver, graphqlDriver, ...(options.drivers || [])])
32
38
  this.drivers.set(driver.type, driver);
39
+ this.authentication = new ToolAuthentication(options.credentials, options.resolveSecret);
40
+ this.connectionService = new ToolConnections(this, this.drivers, options.credentials);
41
+ this.authorization = new ToolAuthorization(options.credentials, (input, guard) => this.connectionService.connect(input, guard));
33
42
  const tools = [];
34
43
  const actions = [];
35
44
  for (const definition of options.systemTools || []) {
@@ -59,7 +68,7 @@ class Toolbox {
59
68
  ...(options.onDeployment ? { onDeployment: options.onDeployment } : {}),
60
69
  });
61
70
  this.deploymentService.adoptLegacy();
62
- this.view = new ToolboxView(() => this.catalog(), this.drivers);
71
+ this.view = new ToolboxView(() => this.catalog(), this.drivers, { resolveSecret: this.authentication.resolve });
63
72
  this.projection.boot();
64
73
  }
65
74
  catalog() {
@@ -84,9 +93,10 @@ class Toolbox {
84
93
  list(loadout) { return this.view.list(loadout); }
85
94
  /** Pin one exact deployment revision and loadout for an execution. */
86
95
  prepare(revisionId, loadout) {
87
- const catalog = preparedCatalog(this.catalog(), revisionId, loadout);
88
- return new ToolboxView(() => structuredClone(catalog), new Map(this.drivers));
96
+ return preparedView(() => this.catalog(), revisionId, loadout, this.drivers, { resolveSecret: this.authentication.resolve });
89
97
  }
98
+ connect(input) { return this.connectionService.connect(input); }
99
+ disconnect(toolId) { return this.connectionService.disconnect(toolId); }
90
100
  query(filters = {}) { return this.view.query(filters); }
91
101
  callable(loadout, filters = {}) { return this.view.callable(loadout, filters); }
92
102
  get(toolId) { return this.view.get(toolId); }
@@ -121,8 +131,12 @@ class Toolbox {
121
131
  || this.system.actions.some((action) => action.id === value))
122
132
  throw new Error(`System record is immutable: ${value}`);
123
133
  const tool = this.get(value);
124
- if (tool)
125
- return tool.tool.status === status ? tool.tool : (await this.update(value, { status })).tool;
134
+ if (tool) {
135
+ const result = tool.tool.status === status ? tool.tool : (await this.update(value, { status })).tool;
136
+ if (status === 'disabled')
137
+ await this.connectionService.forget(tool.tool);
138
+ return result;
139
+ }
126
140
  const action = this.action(value);
127
141
  if (!action)
128
142
  throw new Error(`Unknown tool or action: ${value}`);
@@ -141,6 +155,7 @@ class Toolbox {
141
155
  const tool = this.get(value);
142
156
  if (tool) {
143
157
  await this.deploymentService.activateLocal(null, value);
158
+ await this.connectionService.forget(tool.tool);
144
159
  return tool.tool;
145
160
  }
146
161
  return removeAction(this, value);
@@ -160,12 +175,8 @@ class Toolbox {
160
175
  deploymentSurface() {
161
176
  return this.deploymentService.surface();
162
177
  }
163
- connections(loadout) {
164
- return this.view.connections(loadout);
165
- }
166
- async call(actionId, input = {}, options = {}) {
167
- return this.view.call(actionId, input, options);
168
- }
178
+ connections(loadout) { return this.view.connections(loadout); }
179
+ async call(actionId, input = {}, options = {}) { return this.view.call(actionId, input, options); }
169
180
  hasDriver(tool) { return this.view.hasDriver(tool); }
170
181
  async callMcp(name, input = {}, options = {}) {
171
182
  return this.view.callMcp(name, input, options);
package/dist/types.d.ts CHANGED
@@ -1,4 +1,6 @@
1
+ import type { McpOptions, McpTool } from './mcp-types.js';
1
2
  import type { Writable } from 'node:stream';
3
+ import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
2
4
  import type { ToolDeploymentActivation } from './deployment-types.js';
3
5
  type JsonSchema = {
4
6
  type: 'object';
@@ -12,7 +14,7 @@ type JsonSchema = {
12
14
  description?: string;
13
15
  [key: string]: unknown;
14
16
  };
15
- type ToolType = 'cli' | 'api' | 'mcp';
17
+ type ToolType = 'cli' | 'api' | 'graphql' | 'mcp';
16
18
  type Origin = 'user' | 'catalog' | 'system';
17
19
  type Status = 'enabled' | 'disabled';
18
20
  type SecretReferences = Record<string, string>;
@@ -33,6 +35,13 @@ interface ApiSource extends BaseSource {
33
35
  type: 'api';
34
36
  baseUrl: string;
35
37
  secretHeaders?: SecretReferences;
38
+ secretQuery?: SecretReferences;
39
+ }
40
+ interface GraphqlSource extends BaseSource {
41
+ type: 'graphql';
42
+ url: string;
43
+ secretHeaders?: SecretReferences;
44
+ secretQuery?: SecretReferences;
36
45
  }
37
46
  interface McpSource extends BaseSource {
38
47
  type: 'mcp';
@@ -45,9 +54,10 @@ interface McpSource extends BaseSource {
45
54
  /** Absolute path mounted by the composing host for `transport: host`. */
46
55
  route?: string;
47
56
  secretHeaders?: SecretReferences;
57
+ secretQuery?: SecretReferences;
48
58
  secretEnv?: SecretReferences;
49
59
  }
50
- type ToolSource = CliSource | ApiSource | McpSource;
60
+ type ToolSource = CliSource | ApiSource | GraphqlSource | McpSource;
51
61
  interface CliTarget {
52
62
  args?: string[];
53
63
  }
@@ -58,7 +68,11 @@ interface ApiTarget {
58
68
  interface McpTarget {
59
69
  name: string;
60
70
  }
61
- type ActionTarget = CliTarget | ApiTarget | McpTarget;
71
+ interface GraphqlTarget {
72
+ document: string;
73
+ operationName?: string;
74
+ }
75
+ type ActionTarget = CliTarget | ApiTarget | GraphqlTarget | McpTarget;
62
76
  interface ActionDefinition {
63
77
  name: string;
64
78
  id?: string;
@@ -94,7 +108,7 @@ interface ToolQuery {
94
108
  status?: Status;
95
109
  }
96
110
  type ToolPatch = Omit<Partial<ToolDefinition>, 'id' | 'source'> & {
97
- source?: Partial<CliSource> | Partial<ApiSource> | Partial<McpSource>;
111
+ source?: Partial<CliSource> | Partial<ApiSource> | Partial<GraphqlSource> | Partial<McpSource>;
98
112
  };
99
113
  type ActionPatch = Omit<Partial<ActionDefinition>, 'id'>;
100
114
  interface ToolRecord extends Omit<ToolDefinition, 'actions'> {
@@ -127,16 +141,15 @@ interface ApplyResult {
127
141
  tool: ToolRecord;
128
142
  actions: ActionRecord[];
129
143
  }
144
+ type ToolExposure = 'direct' | 'search' | 'hidden';
130
145
  interface Loadout {
131
- toolIds: string[];
146
+ toolIds: readonly string[];
147
+ exposure?: Readonly<Record<string, ToolExposure>>;
132
148
  }
133
149
  type LoadoutInput = Loadout | string[];
134
150
  interface ToolResult {
135
- content: Array<{
136
- type: 'text';
137
- text: string;
138
- }>;
139
- structuredContent?: unknown;
151
+ content: CallToolResult['content'];
152
+ structuredContent?: Record<string, unknown>;
140
153
  isError?: boolean;
141
154
  truncated?: boolean;
142
155
  }
@@ -157,6 +170,7 @@ interface ToolDriver {
157
170
  type: ToolType;
158
171
  supports?(tool: ToolRecord): boolean;
159
172
  call(request: DriverCall): Promise<ToolResult>;
173
+ discover?(tool: ToolRecord, options: CallOptions): Promise<ActionDefinition[]>;
160
174
  }
161
175
  interface ToolboxOptions {
162
176
  stateDir?: string;
@@ -167,24 +181,17 @@ interface ToolboxOptions {
167
181
  drivers?: ToolDriver[];
168
182
  /** Host-supplied process environment for one CLI tool call, such as where its linked app listens. */
169
183
  environment?: (tool: ToolRecord) => Record<string, string> | Promise<Record<string, string>>;
184
+ credentials?: import('./connection-types.js').ToolCredentialStore;
185
+ resolveSecret?: SecretResolver;
170
186
  onChange?: (catalog: Catalog) => void | Promise<void>;
171
187
  /** Outbound local Live operation. Remote application never calls it. */
172
188
  onDeployment?: (activation: ToolDeploymentActivation) => void | Promise<void>;
173
189
  }
174
- interface McpTool {
175
- name: string;
176
- description: string;
177
- inputSchema: JsonSchema;
178
- handler(input?: Record<string, unknown>): Promise<ToolResult>;
179
- }
180
- interface McpOptions extends CallOptions {
181
- includeManagement?: boolean;
182
- }
183
190
  interface CliIo {
184
191
  stdout?: Writable;
185
192
  stderr?: Writable;
186
193
  commands?: import('./commands.js').ToolCommands;
187
194
  }
188
- export type { ActionDefinition, ActionRecord, ActionTarget, ApiSource, ApiTarget, ApplyResult, CallOptions, Catalog, CliIo, CliSource, CliTarget, DriverCall, JsonSchema, Loadout, LoadoutInput, McpOptions, McpSource, McpTarget, McpTool, Origin, SecretResolver, Status, ToolDefinition, ToolDriver, ToolboxOptions, ToolRecord, ToolResult, ToolPatch, ActionPatch, ToolQuery, ToolSource, ToolType, };
195
+ export type { ActionDefinition, ActionRecord, ActionTarget, ApiSource, ApiTarget, ApplyResult, CallOptions, Catalog, CliIo, CliSource, CliTarget, DriverCall, JsonSchema, GraphqlSource, GraphqlTarget, Loadout, LoadoutInput, McpOptions, McpSource, McpTarget, McpTool, Origin, SecretResolver, Status, ToolDefinition, ToolDriver, ToolboxOptions, ToolRecord, ToolResult, ToolPatch, ActionPatch, ToolQuery, ToolSource, ToolType, ToolExposure, };
189
196
  export type { ToolDeployment, ToolDeploymentActivation, ToolDeploymentSnapshot, ToolDeploymentSurface, } from './deployment-types.js';
190
197
  export type { HostMcpToolDefinitionInput, HostMcpToolDescriptor } from './host-mcp-tool.js';
@@ -10,7 +10,7 @@ adapters.
10
10
  - stable tool and action identity;
11
11
  - immutable deployment history and current deployment heads;
12
12
  - loadout selection and deterministic MCP names;
13
- - CLI and API drivers, validation, cancellation, and output bounds;
13
+ - CLI, API, GraphQL, and MCP driver contracts, validation, cancellation, and output bounds;
14
14
  - the Toolbox management MCP surface; and
15
15
  - the versioned `deployment.activate` Live surface.
16
16
 
@@ -19,12 +19,17 @@ adapters.
19
19
  - the exact `@amalgm/tools` package version in the Shell release;
20
20
  - the one host MCP driver and authenticated loopback routes;
21
21
  - machine-local SQLite placement and the portable deployment directory;
22
- - execution-time credential resolution;
22
+ - encrypted credential persistence and upstream MCP transports;
23
23
  - projection of owning products' official MCP descriptors as immutable system
24
24
  tools; and
25
25
  - binding Tools' deployment surface to broader product state when enabled.
26
26
 
27
- Agents stores loadout identifiers; Chat pins the exact Toolbox `revisionId`
27
+ Tools owns connection transitions and OAuth refresh; Shell supplies the encrypted
28
+ vault without duplicating a connection registry. Definitions and actions remain
29
+ in `users/<email>/toolbox/<tool-id>/deployments`; vault records remain under the
30
+ machine boundary and never enter synced deployment documents.
31
+
32
+ Agents stores loadout identifiers and direct/search/hidden exposure; Chat pins the exact Toolbox `revisionId`
28
33
  during preparation. Neither product writes Tools persistence.
29
34
 
30
35
  ## First-party products and Channels
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amalgm/tools",
3
- "version": "0.1.7-preview.34746901886",
3
+ "version": "0.1.7-preview.34938534039",
4
4
  "description": "Local-first tool definitions, Toolbox registry, and agent execution surfaces.",
5
5
  "license": "UNLICENSED",
6
6
  "private": false,
@@ -57,6 +57,7 @@
57
57
  },
58
58
  "dependencies": {
59
59
  "@amalgm/core": "0.5.1-preview.34403852460",
60
+ "@modelcontextprotocol/sdk": "1.30.0",
60
61
  "better-sqlite3": "^12.6.2"
61
62
  },
62
63
  "devDependencies": {
@@ -87,11 +88,11 @@
87
88
  "package.json"
88
89
  ]
89
90
  },
90
- "gitHead": "533a3b433b0aa5c4036fd0b90496472b6081d0a5",
91
+ "gitHead": "f5da1898ae08a6531db09197968c1a7134b209f8",
91
92
  "amalgmSource": {
92
93
  "repository": "amalgm-inc/amalgm-tools",
93
94
  "branch": "preview",
94
- "commit": "533a3b433b0aa5c4036fd0b90496472b6081d0a5",
95
- "occurrence": "34746901886"
95
+ "commit": "f5da1898ae08a6531db09197968c1a7134b209f8",
96
+ "occurrence": "34938534039"
96
97
  }
97
98
  }