@amalgm/tools 0.1.7-main.34746904064 → 0.1.7-main.34938545892
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 +29 -1
- package/README.md +35 -5
- package/dist/api-driver.d.ts +2 -1
- package/dist/api-driver.js +67 -48
- package/dist/cli-driver.d.ts +4 -3
- package/dist/cli-driver.js +43 -40
- package/dist/cli.d.ts +7 -2
- package/dist/cli.js +51 -49
- package/dist/commands.d.ts +27 -0
- package/dist/commands.js +16 -0
- package/dist/connection-auth.d.ts +11 -0
- package/dist/connection-auth.js +98 -0
- package/dist/connection-source.d.ts +23 -0
- package/dist/connection-source.js +62 -0
- package/dist/connection-types.d.ts +34 -0
- package/dist/connection-types.js +1 -0
- package/dist/connections.d.ts +14 -0
- package/dist/connections.js +98 -0
- package/dist/credential-operations.d.ts +7 -0
- package/dist/credential-operations.js +37 -0
- package/dist/definition.js +11 -3
- package/dist/host-mcp-tool.d.ts +18 -1
- package/dist/http-mutations.d.ts +63 -0
- package/dist/http-mutations.js +41 -0
- package/dist/http.d.ts +2 -3
- package/dist/http.js +9 -3
- package/dist/ids.d.ts +3 -1
- package/dist/ids.js +7 -2
- package/dist/index.d.ts +8 -0
- package/dist/index.js +4 -0
- package/dist/input.js +7 -32
- package/dist/loadout.d.ts +3 -0
- package/dist/loadout.js +23 -0
- package/dist/mcp-driver.d.ts +16 -0
- package/dist/mcp-driver.js +44 -0
- package/dist/mcp-search.d.ts +8 -0
- package/dist/mcp-search.js +51 -0
- package/dist/mcp-types.d.ts +13 -0
- package/dist/mcp-types.js +1 -0
- package/dist/mcp.d.ts +1 -1
- package/dist/mcp.js +49 -26
- package/dist/oauth.d.ts +29 -0
- package/dist/oauth.js +131 -0
- package/dist/prepared-catalog.d.ts +3 -1
- package/dist/prepared-catalog.js +20 -1
- package/dist/results.d.ts +4 -1
- package/dist/results.js +21 -16
- package/dist/selection.js +3 -0
- package/dist/toolbox-view.d.ts +4 -1
- package/dist/toolbox-view.js +8 -2
- package/dist/toolbox.d.ts +12 -2
- package/dist/toolbox.js +32 -16
- package/dist/types.d.ts +33 -37
- package/dist/updates.d.ts +7 -2
- package/dist/updates.js +15 -1
- package/docs/SHELL_INTEGRATION.md +8 -3
- package/package.json +5 -4
- package/skills/tools/SKILL.md +6 -0
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { credentialOperations } from './credential-operations.js';
|
|
2
|
+
export function validateCredential(value) {
|
|
3
|
+
if (value.type === 'secret') {
|
|
4
|
+
if (typeof value.value !== 'string' || !value.value)
|
|
5
|
+
throw new Error('A non-empty tool secret is required');
|
|
6
|
+
return { type: 'secret', value: value.value };
|
|
7
|
+
}
|
|
8
|
+
if (value.type !== 'oauth' || !value.accessToken || !value.clientId || !value.tokenUrl) {
|
|
9
|
+
throw new Error('OAuth requires accessToken, clientId, and tokenUrl');
|
|
10
|
+
}
|
|
11
|
+
const url = new URL(value.tokenUrl);
|
|
12
|
+
if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password)
|
|
13
|
+
throw new Error('Invalid OAuth token endpoint');
|
|
14
|
+
if (value.expiresAt && !Number.isFinite(Date.parse(value.expiresAt)))
|
|
15
|
+
throw new Error('Invalid OAuth token expiry');
|
|
16
|
+
if (value.tokenEndpointAuthMethod && !['none', 'client_secret_basic', 'client_secret_post'].includes(value.tokenEndpointAuthMethod)) {
|
|
17
|
+
throw new Error('Unsupported OAuth token endpoint authentication');
|
|
18
|
+
}
|
|
19
|
+
return structuredClone(value);
|
|
20
|
+
}
|
|
21
|
+
async function refresh(current) {
|
|
22
|
+
if (!current.refreshToken)
|
|
23
|
+
throw new Error('Tool authorization expired; reconnect the tool');
|
|
24
|
+
const body = new URLSearchParams({ grant_type: 'refresh_token', refresh_token: current.refreshToken, client_id: current.clientId });
|
|
25
|
+
const headers = { 'content-type': 'application/x-www-form-urlencoded' };
|
|
26
|
+
if (current.clientSecret) {
|
|
27
|
+
if (current.tokenEndpointAuthMethod === 'client_secret_basic') {
|
|
28
|
+
headers.Authorization = `Basic ${Buffer.from(`${encodeURIComponent(current.clientId)}:${encodeURIComponent(current.clientSecret)}`).toString('base64')}`;
|
|
29
|
+
}
|
|
30
|
+
else
|
|
31
|
+
body.set('client_secret', current.clientSecret);
|
|
32
|
+
}
|
|
33
|
+
if (current.scope)
|
|
34
|
+
body.set('scope', current.scope);
|
|
35
|
+
if (current.resource)
|
|
36
|
+
body.set('resource', current.resource);
|
|
37
|
+
const response = await fetch(current.tokenUrl, {
|
|
38
|
+
method: 'POST', headers, body, redirect: 'manual', signal: AbortSignal.timeout(15_000),
|
|
39
|
+
});
|
|
40
|
+
if (!response.ok)
|
|
41
|
+
throw new Error(`Tool authorization refresh failed (${response.status}); reconnect the tool`);
|
|
42
|
+
const value = await response.json();
|
|
43
|
+
if (typeof value.access_token !== 'string' || !value.access_token)
|
|
44
|
+
throw new Error('OAuth refresh returned no access token');
|
|
45
|
+
if (value.token_type && String(value.token_type).toLowerCase() !== 'bearer')
|
|
46
|
+
throw new Error('Unsupported OAuth token type');
|
|
47
|
+
const { expiresAt: _previousExpiry, ...retained } = current;
|
|
48
|
+
return {
|
|
49
|
+
...retained, accessToken: value.access_token,
|
|
50
|
+
...(typeof value.refresh_token === 'string' && value.refresh_token ? { refreshToken: value.refresh_token } : {}),
|
|
51
|
+
...(typeof value.expires_in === 'number' && value.expires_in > 0 ? { expiresAt: new Date(Date.now() + value.expires_in * 1000).toISOString() } : {}),
|
|
52
|
+
...(typeof value.scope === 'string' ? { scope: value.scope } : {}),
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
/** Token refresh belongs to the connection; encryption belongs to the host. */
|
|
56
|
+
export class ToolAuthentication {
|
|
57
|
+
store;
|
|
58
|
+
fallback;
|
|
59
|
+
#refreshing = new Map();
|
|
60
|
+
constructor(store, fallback) {
|
|
61
|
+
this.store = store;
|
|
62
|
+
this.fallback = fallback;
|
|
63
|
+
this.store = store && credentialOperations(store);
|
|
64
|
+
}
|
|
65
|
+
resolve = async (reference) => {
|
|
66
|
+
if (!reference.startsWith('tools:'))
|
|
67
|
+
return this.fallback?.(reference);
|
|
68
|
+
const pending = this.#refreshing.get(reference);
|
|
69
|
+
if (pending)
|
|
70
|
+
return pending;
|
|
71
|
+
const work = this.#resolve(reference);
|
|
72
|
+
this.#refreshing.set(reference, work);
|
|
73
|
+
try {
|
|
74
|
+
return await work;
|
|
75
|
+
}
|
|
76
|
+
finally {
|
|
77
|
+
if (this.#refreshing.get(reference) === work)
|
|
78
|
+
this.#refreshing.delete(reference);
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
async #resolve(reference) {
|
|
82
|
+
const encoded = await this.store?.get(reference);
|
|
83
|
+
if (encoded === undefined)
|
|
84
|
+
return undefined;
|
|
85
|
+
const credential = validateCredential(JSON.parse(encoded));
|
|
86
|
+
if (credential.type === 'secret')
|
|
87
|
+
return credential.value;
|
|
88
|
+
if (!credential.expiresAt || Date.parse(credential.expiresAt) > Date.now() + 30_000) {
|
|
89
|
+
return `Bearer ${credential.accessToken}`;
|
|
90
|
+
}
|
|
91
|
+
const renewed = await refresh(credential);
|
|
92
|
+
// A disconnect or a new authorization wins over an in-flight refresh.
|
|
93
|
+
if (!await credentialOperations(this.store).replace(reference, encoded, JSON.stringify(renewed))) {
|
|
94
|
+
throw new Error('Tool authorization changed during refresh');
|
|
95
|
+
}
|
|
96
|
+
return `Bearer ${renewed.accessToken}`;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { ConnectToolInput } from './connection-types.js';
|
|
2
|
+
import type { ActionDefinition, ToolSource } from './types.js';
|
|
3
|
+
export declare function sourceReferences(source: ToolSource): string[];
|
|
4
|
+
/** Credentials are authority-bound references, never portable definition bytes. */
|
|
5
|
+
export declare function connectionSource(input: ConnectToolInput): {
|
|
6
|
+
definition: {
|
|
7
|
+
source: ToolSource;
|
|
8
|
+
status: "enabled";
|
|
9
|
+
actions: ActionDefinition[];
|
|
10
|
+
origin: import("./types.js").Origin;
|
|
11
|
+
owner: string;
|
|
12
|
+
createdAt: string;
|
|
13
|
+
updatedAt: string;
|
|
14
|
+
description?: string | undefined;
|
|
15
|
+
name: string;
|
|
16
|
+
id: string;
|
|
17
|
+
policy?: Record<string, unknown> | undefined;
|
|
18
|
+
metadata?: Record<string, unknown> | undefined;
|
|
19
|
+
appId?: string | undefined;
|
|
20
|
+
display?: Record<string, unknown> | undefined;
|
|
21
|
+
};
|
|
22
|
+
staged: Map<string, string>;
|
|
23
|
+
};
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { canonicalJson } from './deployments.js';
|
|
3
|
+
import { normalizeDefinition } from './definition.js';
|
|
4
|
+
import { validateCredential } from './connection-auth.js';
|
|
5
|
+
export function sourceReferences(source) {
|
|
6
|
+
return [...new Set([
|
|
7
|
+
...('secretHeaders' in source ? Object.values(source.secretHeaders || {}) : []),
|
|
8
|
+
...('secretQuery' in source ? Object.values(source.secretQuery || {}) : []),
|
|
9
|
+
...('secretEnv' in source ? Object.values(source.secretEnv || {}) : []),
|
|
10
|
+
])];
|
|
11
|
+
}
|
|
12
|
+
/** Credentials are authority-bound references, never portable definition bytes. */
|
|
13
|
+
export function connectionSource(input) {
|
|
14
|
+
const { tool, actions } = normalizeDefinition(input.definition);
|
|
15
|
+
if (tool.origin === 'system' || (tool.source.type === 'mcp' && tool.source.transport === 'host')) {
|
|
16
|
+
throw new Error('Host-owned tools cannot be connected by a user');
|
|
17
|
+
}
|
|
18
|
+
const source = structuredClone(tool.source);
|
|
19
|
+
const identity = { ...source };
|
|
20
|
+
delete identity.secretHeaders;
|
|
21
|
+
delete identity.secretEnv;
|
|
22
|
+
delete identity.secretQuery;
|
|
23
|
+
const authority = createHash('sha256').update(canonicalJson(identity)).digest('hex').slice(0, 24);
|
|
24
|
+
const prefix = `tools:${tool.id}:${authority}:`;
|
|
25
|
+
const staged = new Map();
|
|
26
|
+
const add = (surface, name, value) => {
|
|
27
|
+
if (!name || /[\r\n]/.test(name))
|
|
28
|
+
throw new Error('Invalid tool credential field');
|
|
29
|
+
const field = surface === 'headers' ? 'secretHeaders' : surface === 'query' ? 'secretQuery' : 'secretEnv';
|
|
30
|
+
if (surface !== 'env' && (source.type === 'cli' || (source.type === 'mcp' && source.transport === 'stdio'))) {
|
|
31
|
+
throw new Error('This tool uses environment credentials, not HTTP headers');
|
|
32
|
+
}
|
|
33
|
+
if (surface === 'env' && source.type !== 'cli' && !(source.type === 'mcp' && source.transport === 'stdio')) {
|
|
34
|
+
throw new Error('This tool uses HTTP header credentials, not environment variables');
|
|
35
|
+
}
|
|
36
|
+
const target = source;
|
|
37
|
+
const refs = { ...target[field] };
|
|
38
|
+
const canonicalName = surface === 'headers' ? name.toLowerCase() : name;
|
|
39
|
+
for (const existing of Object.keys(refs))
|
|
40
|
+
if ((surface === 'headers' ? existing.toLowerCase() : existing) === canonicalName)
|
|
41
|
+
delete refs[existing];
|
|
42
|
+
const reference = `${prefix}${surface}:${canonicalName}`;
|
|
43
|
+
refs[name] = reference;
|
|
44
|
+
target[field] = refs;
|
|
45
|
+
staged.set(reference, JSON.stringify(validateCredential(value)));
|
|
46
|
+
};
|
|
47
|
+
for (const [name, value] of Object.entries(input.credentials?.headers || {}))
|
|
48
|
+
add('headers', name, { type: 'secret', value });
|
|
49
|
+
for (const [name, value] of Object.entries(input.credentials?.query || {}))
|
|
50
|
+
add('query', name, { type: 'secret', value });
|
|
51
|
+
for (const [name, value] of Object.entries(input.credentials?.env || {}))
|
|
52
|
+
add('env', name, { type: 'secret', value });
|
|
53
|
+
if (input.credentials?.oauth) {
|
|
54
|
+
const resource = source.type === 'mcp' ? source.url : source.type === 'graphql' ? source.url : source.type === 'api' ? source.baseUrl : undefined;
|
|
55
|
+
add('headers', 'Authorization', { ...input.credentials.oauth, type: 'oauth', ...(resource ? { resource } : {}) });
|
|
56
|
+
}
|
|
57
|
+
for (const ref of sourceReferences(source)) {
|
|
58
|
+
if (!ref.startsWith(prefix))
|
|
59
|
+
throw new Error('Tool credential reference belongs to another source; reconnect with its credentials');
|
|
60
|
+
}
|
|
61
|
+
return { definition: { ...tool, source, status: 'enabled', actions: actions }, staged };
|
|
62
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { ToolDefinition } from './types.js';
|
|
2
|
+
/** The host owns encryption and physical persistence; Tools owns these bytes. */
|
|
3
|
+
export interface ToolCredentialStore {
|
|
4
|
+
get(reference: string): string | undefined | Promise<string | undefined>;
|
|
5
|
+
set(reference: string, value: string): void | Promise<void>;
|
|
6
|
+
delete(reference: string): void | Promise<void>;
|
|
7
|
+
}
|
|
8
|
+
export interface OAuthCredential {
|
|
9
|
+
type: 'oauth';
|
|
10
|
+
accessToken: string;
|
|
11
|
+
refreshToken?: string;
|
|
12
|
+
expiresAt?: string;
|
|
13
|
+
tokenUrl: string;
|
|
14
|
+
clientId: string;
|
|
15
|
+
clientSecret?: string;
|
|
16
|
+
tokenEndpointAuthMethod?: 'client_secret_basic' | 'client_secret_post' | 'none';
|
|
17
|
+
scope?: string;
|
|
18
|
+
resource?: string;
|
|
19
|
+
}
|
|
20
|
+
export type ToolCredential = {
|
|
21
|
+
type: 'secret';
|
|
22
|
+
value: string;
|
|
23
|
+
} | OAuthCredential;
|
|
24
|
+
export interface ConnectionCredentials {
|
|
25
|
+
headers?: Record<string, string>;
|
|
26
|
+
query?: Record<string, string>;
|
|
27
|
+
env?: Record<string, string>;
|
|
28
|
+
oauth?: OAuthCredential;
|
|
29
|
+
}
|
|
30
|
+
export interface ConnectToolInput {
|
|
31
|
+
definition: ToolDefinition;
|
|
32
|
+
/** Write-only. Values never enter the definition, response, or deployment. */
|
|
33
|
+
credentials?: ConnectionCredentials;
|
|
34
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { ConnectToolInput, ToolCredentialStore } from './connection-types.js';
|
|
2
|
+
import type { Toolbox } from './toolbox.js';
|
|
3
|
+
import type { ToolDriver, ToolRecord } from './types.js';
|
|
4
|
+
/** Connection transitions mutate the one Toolbox and the host-owned vault. */
|
|
5
|
+
export declare class ToolConnections {
|
|
6
|
+
#private;
|
|
7
|
+
private readonly toolbox;
|
|
8
|
+
private readonly drivers;
|
|
9
|
+
private readonly store?;
|
|
10
|
+
constructor(toolbox: Toolbox, drivers: ReadonlyMap<string, ToolDriver>, store?: ToolCredentialStore | undefined);
|
|
11
|
+
connect(input: ConnectToolInput, guard?: () => Promise<void>): Promise<import("./types.js").ApplyResult>;
|
|
12
|
+
disconnect(toolId: string): Promise<import("./types.js").ApplyResult>;
|
|
13
|
+
forget(tool: ToolRecord, retained?: Set<string>): Promise<void>;
|
|
14
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { credentialOperations } from './credential-operations.js';
|
|
2
|
+
import { ToolAuthentication } from './connection-auth.js';
|
|
3
|
+
import { authorizationReference } from './oauth.js';
|
|
4
|
+
import { connectionSource, sourceReferences } from './connection-source.js';
|
|
5
|
+
/** Connection transitions mutate the one Toolbox and the host-owned vault. */
|
|
6
|
+
export class ToolConnections {
|
|
7
|
+
toolbox;
|
|
8
|
+
drivers;
|
|
9
|
+
store;
|
|
10
|
+
#pending = new Map();
|
|
11
|
+
constructor(toolbox, drivers, store) {
|
|
12
|
+
this.toolbox = toolbox;
|
|
13
|
+
this.drivers = drivers;
|
|
14
|
+
this.store = store;
|
|
15
|
+
this.store = store && credentialOperations(store);
|
|
16
|
+
}
|
|
17
|
+
connect(input, guard) {
|
|
18
|
+
const { definition, staged } = connectionSource(input);
|
|
19
|
+
return this.#ordered(definition.id, async () => {
|
|
20
|
+
await guard?.();
|
|
21
|
+
if (this.toolbox.isSystemTool(definition.id))
|
|
22
|
+
throw new Error('System tools are immutable');
|
|
23
|
+
if (staged.size && !this.store)
|
|
24
|
+
throw new Error('Tool credential vault is unavailable');
|
|
25
|
+
const previous = this.toolbox.get(definition.id)?.tool;
|
|
26
|
+
const original = new Map();
|
|
27
|
+
const overlay = {
|
|
28
|
+
get: (ref) => staged.has(ref) ? staged.get(ref) : this.store?.get(ref),
|
|
29
|
+
set: (ref, value) => { staged.set(ref, value); },
|
|
30
|
+
delete: (ref) => { staged.delete(ref); },
|
|
31
|
+
};
|
|
32
|
+
const auth = new ToolAuthentication(overlay);
|
|
33
|
+
for (const ref of sourceReferences(definition.source)) {
|
|
34
|
+
if (await auth.resolve(ref) === undefined)
|
|
35
|
+
throw new Error('Tool authorization is missing; reconnect with credentials');
|
|
36
|
+
}
|
|
37
|
+
const driver = this.drivers.get(definition.source.type);
|
|
38
|
+
if (!driver || !(driver.supports?.(definition) ?? true))
|
|
39
|
+
throw new Error(`No ${definition.source.type} driver is configured`);
|
|
40
|
+
if (definition.source.type === 'mcp') {
|
|
41
|
+
if (!driver.discover)
|
|
42
|
+
throw new Error('MCP action discovery is unavailable');
|
|
43
|
+
definition.actions = await driver.discover(definition, { resolveSecret: auth.resolve });
|
|
44
|
+
}
|
|
45
|
+
try {
|
|
46
|
+
await guard?.();
|
|
47
|
+
for (const [ref, value] of staged) {
|
|
48
|
+
original.set(ref, await this.store.get(ref));
|
|
49
|
+
await this.store.set(ref, value);
|
|
50
|
+
}
|
|
51
|
+
const result = await this.toolbox.apply(definition);
|
|
52
|
+
await this.store?.delete(authorizationReference(definition.id));
|
|
53
|
+
if (previous) {
|
|
54
|
+
const retained = new Set(sourceReferences(result.tool.source));
|
|
55
|
+
await this.forget(previous, retained);
|
|
56
|
+
}
|
|
57
|
+
return result;
|
|
58
|
+
}
|
|
59
|
+
catch (error) {
|
|
60
|
+
for (const [ref, value] of original) {
|
|
61
|
+
if (value === undefined)
|
|
62
|
+
await this.store.delete(ref);
|
|
63
|
+
else
|
|
64
|
+
await this.store.set(ref, value);
|
|
65
|
+
}
|
|
66
|
+
throw error;
|
|
67
|
+
}
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
disconnect(toolId) {
|
|
71
|
+
return this.#ordered(toolId, async () => {
|
|
72
|
+
const current = this.toolbox.get(toolId);
|
|
73
|
+
if (!current)
|
|
74
|
+
throw new Error(`Unknown tool: ${toolId}`);
|
|
75
|
+
await this.toolbox.setStatus(toolId, 'disabled');
|
|
76
|
+
return this.toolbox.get(toolId);
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
async forget(tool, retained = new Set()) {
|
|
80
|
+
await this.store?.delete(authorizationReference(tool.id));
|
|
81
|
+
for (const ref of sourceReferences(tool.source)) {
|
|
82
|
+
if (ref.startsWith(`tools:${tool.id}:`) && !retained.has(ref))
|
|
83
|
+
await this.store?.delete(ref);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
async #ordered(key, operation) {
|
|
87
|
+
const previous = this.#pending.get(key) || Promise.resolve();
|
|
88
|
+
const current = previous.catch(() => undefined).then(operation);
|
|
89
|
+
this.#pending.set(key, current);
|
|
90
|
+
try {
|
|
91
|
+
return await current;
|
|
92
|
+
}
|
|
93
|
+
finally {
|
|
94
|
+
if (this.#pending.get(key) === current)
|
|
95
|
+
this.#pending.delete(key);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { ToolCredentialStore } from './connection-types.js';
|
|
2
|
+
interface SerializedStore extends ToolCredentialStore {
|
|
3
|
+
replace(reference: string, expected: string | undefined, value: string | undefined): Promise<boolean>;
|
|
4
|
+
}
|
|
5
|
+
/** All credential writes share an order; a stale refresh never recreates a deletion. */
|
|
6
|
+
export declare function credentialOperations(store: ToolCredentialStore): SerializedStore;
|
|
7
|
+
export {};
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
const stores = new WeakMap();
|
|
2
|
+
/** All credential writes share an order; a stale refresh never recreates a deletion. */
|
|
3
|
+
export function credentialOperations(store) {
|
|
4
|
+
const existing = stores.get(store);
|
|
5
|
+
if (existing)
|
|
6
|
+
return existing;
|
|
7
|
+
const pending = new Map();
|
|
8
|
+
async function ordered(reference, operation) {
|
|
9
|
+
const previous = pending.get(reference) || Promise.resolve();
|
|
10
|
+
const current = previous.catch(() => undefined).then(operation);
|
|
11
|
+
pending.set(reference, current);
|
|
12
|
+
try {
|
|
13
|
+
return await current;
|
|
14
|
+
}
|
|
15
|
+
finally {
|
|
16
|
+
if (pending.get(reference) === current)
|
|
17
|
+
pending.delete(reference);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
const wrapper = {
|
|
21
|
+
get: (reference) => ordered(reference, () => store.get(reference)),
|
|
22
|
+
set: (reference, value) => ordered(reference, () => store.set(reference, value)),
|
|
23
|
+
delete: (reference) => ordered(reference, () => store.delete(reference)),
|
|
24
|
+
replace: (reference, expected, value) => ordered(reference, async () => {
|
|
25
|
+
if (await store.get(reference) !== expected)
|
|
26
|
+
return false;
|
|
27
|
+
if (value === undefined)
|
|
28
|
+
await store.delete(reference);
|
|
29
|
+
else
|
|
30
|
+
await store.set(reference, value);
|
|
31
|
+
return true;
|
|
32
|
+
}),
|
|
33
|
+
};
|
|
34
|
+
stores.set(store, wrapper);
|
|
35
|
+
stores.set(wrapper, wrapper);
|
|
36
|
+
return wrapper;
|
|
37
|
+
}
|
package/dist/definition.js
CHANGED
|
@@ -68,15 +68,16 @@ function normalizeSource(source) {
|
|
|
68
68
|
...(refs(source.secretEnv, 'source.secretEnv') ? { secretEnv: refs(source.secretEnv, 'source.secretEnv') } : {}),
|
|
69
69
|
};
|
|
70
70
|
}
|
|
71
|
-
if (source.type === 'api') {
|
|
72
|
-
const url = new URL(string(source.
|
|
71
|
+
if (source.type === 'api' || source.type === 'graphql') {
|
|
72
|
+
const url = new URL(string(source.type === 'api' ? source.baseUrl : source.url, 'source URL'));
|
|
73
73
|
if (!['http:', 'https:'].includes(url.protocol))
|
|
74
74
|
throw new Error('source.baseUrl must use http or https');
|
|
75
75
|
if (url.username || url.password)
|
|
76
76
|
throw new Error('source.baseUrl cannot contain credentials');
|
|
77
77
|
return {
|
|
78
|
-
type: 'api', baseUrl: url.toString(), ...base(source),
|
|
78
|
+
...(source.type === 'api' ? { type: 'api', baseUrl: url.toString() } : { type: 'graphql', url: url.toString() }), ...base(source),
|
|
79
79
|
...(refs(source.secretHeaders, 'source.secretHeaders') ? { secretHeaders: refs(source.secretHeaders, 'source.secretHeaders') } : {}),
|
|
80
|
+
...(refs(source.secretQuery, 'source.secretQuery') ? { secretQuery: refs(source.secretQuery, 'source.secretQuery') } : {}),
|
|
80
81
|
};
|
|
81
82
|
}
|
|
82
83
|
if (source.type === 'mcp') {
|
|
@@ -102,6 +103,7 @@ function normalizeSource(source) {
|
|
|
102
103
|
...(source.serverName ? { serverName: string(source.serverName, 'source.serverName') } : {}),
|
|
103
104
|
...(hostRoute(source.route) ? { route: hostRoute(source.route) } : {}),
|
|
104
105
|
...(refs(source.secretHeaders, 'source.secretHeaders') ? { secretHeaders: refs(source.secretHeaders, 'source.secretHeaders') } : {}),
|
|
106
|
+
...(refs(source.secretQuery, 'source.secretQuery') ? { secretQuery: refs(source.secretQuery, 'source.secretQuery') } : {}),
|
|
105
107
|
...(refs(source.secretEnv, 'source.secretEnv') ? { secretEnv: refs(source.secretEnv, 'source.secretEnv') } : {}),
|
|
106
108
|
};
|
|
107
109
|
}
|
|
@@ -125,6 +127,11 @@ function target(type, value) {
|
|
|
125
127
|
return { ...(strings(raw.args, 'action.target.args') ? { args: strings(raw.args, 'action.target.args') } : {}) };
|
|
126
128
|
if (type === 'api')
|
|
127
129
|
return { method: string(raw.method, 'action.target.method').toUpperCase(), path: string(raw.path, 'action.target.path') };
|
|
130
|
+
if (type === 'graphql')
|
|
131
|
+
return {
|
|
132
|
+
document: string(raw.document, 'action.target.document'),
|
|
133
|
+
...(raw.operationName ? { operationName: string(raw.operationName, 'action.target.operationName') } : {}),
|
|
134
|
+
};
|
|
128
135
|
return { name: string(raw.name, 'action.target.name') };
|
|
129
136
|
}
|
|
130
137
|
function normalizeDefinition(definition, existing, now = new Date().toISOString()) {
|
|
@@ -140,6 +147,7 @@ function normalizeDefinition(definition, existing, now = new Date().toISOString(
|
|
|
140
147
|
owner: definition.owner?.trim() || 'user', origin,
|
|
141
148
|
status: definition.status || 'enabled',
|
|
142
149
|
...(definition.description?.trim() ? { description: definition.description.trim() } : {}),
|
|
150
|
+
...(definition.appId?.trim() ? { appId: definition.appId.trim() } : {}),
|
|
143
151
|
...(definition.display ? { display: structuredClone(definition.display) } : {}),
|
|
144
152
|
...(definition.policy ? { policy: structuredClone(definition.policy) } : {}),
|
|
145
153
|
...(definition.metadata ? { metadata: structuredClone(definition.metadata) } : {}),
|
package/dist/host-mcp-tool.d.ts
CHANGED
|
@@ -1,4 +1,20 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { JsonSchema, ToolDefinition } from './types.js';
|
|
2
|
+
interface HostMcpToolDescriptor {
|
|
3
|
+
name: string;
|
|
4
|
+
description?: string;
|
|
5
|
+
inputSchema?: JsonSchema;
|
|
6
|
+
}
|
|
7
|
+
interface HostMcpToolDefinitionInput {
|
|
8
|
+
id: string;
|
|
9
|
+
name: string;
|
|
10
|
+
description?: string;
|
|
11
|
+
serverName: string;
|
|
12
|
+
route: string;
|
|
13
|
+
tools: readonly HostMcpToolDescriptor[];
|
|
14
|
+
owner?: string;
|
|
15
|
+
display?: Record<string, unknown>;
|
|
16
|
+
metadata?: Record<string, unknown>;
|
|
17
|
+
}
|
|
2
18
|
/**
|
|
3
19
|
* Project an owning SDK's MCP descriptors into one immutable first-party
|
|
4
20
|
* Toolbox tool. The descriptors remain authoritative; this adapter does not
|
|
@@ -6,3 +22,4 @@ import type { HostMcpToolDefinitionInput, ToolDefinition } from './types.js';
|
|
|
6
22
|
*/
|
|
7
23
|
declare function defineHostMcpTool(input: HostMcpToolDefinitionInput): ToolDefinition;
|
|
8
24
|
export { defineHostMcpTool };
|
|
25
|
+
export type { HostMcpToolDefinitionInput, HostMcpToolDescriptor };
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { Toolbox } from './toolbox.js';
|
|
2
|
+
export declare function mutateToolbox(toolbox: Toolbox, method: string, pathname: string, value: unknown): Promise<{
|
|
3
|
+
status: number;
|
|
4
|
+
body: {
|
|
5
|
+
url: string;
|
|
6
|
+
state: string;
|
|
7
|
+
toolId: string;
|
|
8
|
+
};
|
|
9
|
+
} | {
|
|
10
|
+
status: number;
|
|
11
|
+
body: {
|
|
12
|
+
ok: boolean;
|
|
13
|
+
tool?: undefined;
|
|
14
|
+
actions?: undefined;
|
|
15
|
+
deleted?: undefined;
|
|
16
|
+
error?: undefined;
|
|
17
|
+
};
|
|
18
|
+
} | {
|
|
19
|
+
status: number;
|
|
20
|
+
body: {
|
|
21
|
+
ok: boolean;
|
|
22
|
+
tool: {
|
|
23
|
+
type: "cli" | "api" | "graphql" | "mcp";
|
|
24
|
+
origin: import("./types.js").Origin;
|
|
25
|
+
status: import("./types.js").Status;
|
|
26
|
+
owner: string;
|
|
27
|
+
createdAt: string;
|
|
28
|
+
updatedAt: string;
|
|
29
|
+
description?: string | undefined;
|
|
30
|
+
name: string;
|
|
31
|
+
id: string;
|
|
32
|
+
policy?: Record<string, unknown> | undefined;
|
|
33
|
+
metadata?: Record<string, unknown> | undefined;
|
|
34
|
+
appId?: string | undefined;
|
|
35
|
+
source: import("./types.js").ToolSource;
|
|
36
|
+
display?: Record<string, unknown> | undefined;
|
|
37
|
+
};
|
|
38
|
+
actions: import("./types.js").ActionRecord[];
|
|
39
|
+
deleted?: undefined;
|
|
40
|
+
error?: undefined;
|
|
41
|
+
};
|
|
42
|
+
} | {
|
|
43
|
+
status: number;
|
|
44
|
+
body: {
|
|
45
|
+
ok: boolean;
|
|
46
|
+
deleted: boolean;
|
|
47
|
+
tool?: undefined;
|
|
48
|
+
actions?: undefined;
|
|
49
|
+
error?: undefined;
|
|
50
|
+
};
|
|
51
|
+
} | {
|
|
52
|
+
status: number;
|
|
53
|
+
body: import("./types.js").ToolResult;
|
|
54
|
+
} | {
|
|
55
|
+
status: number;
|
|
56
|
+
body: {
|
|
57
|
+
error: string;
|
|
58
|
+
ok?: undefined;
|
|
59
|
+
tool?: undefined;
|
|
60
|
+
actions?: undefined;
|
|
61
|
+
deleted?: undefined;
|
|
62
|
+
};
|
|
63
|
+
}>;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
export async function mutateToolbox(toolbox, method, pathname, value) {
|
|
2
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
3
|
+
throw new Error('Toolbox request must be an object');
|
|
4
|
+
const body = value;
|
|
5
|
+
if (pathname === '/toolbox/oauth/authorize' && method === 'POST') {
|
|
6
|
+
return { status: 200, body: await toolbox.authorization.begin(body) };
|
|
7
|
+
}
|
|
8
|
+
if (pathname === '/toolbox/oauth/callback' && method === 'POST') {
|
|
9
|
+
await toolbox.authorization.complete({ state: String(body.state || ''), code: String(body.code || '') });
|
|
10
|
+
return { status: 200, body: { ok: true } };
|
|
11
|
+
}
|
|
12
|
+
if (pathname === '/toolbox/tools') {
|
|
13
|
+
if (method === 'POST') {
|
|
14
|
+
const result = await toolbox.connect(body);
|
|
15
|
+
return { status: 200, body: { ok: true, tool: { ...result.tool, type: result.tool.source.type }, actions: result.actions } };
|
|
16
|
+
}
|
|
17
|
+
if (method === 'PATCH') {
|
|
18
|
+
const toolId = typeof body.id === 'string' ? body.id : '';
|
|
19
|
+
if (body.status === 'disabled') {
|
|
20
|
+
const result = await toolbox.disconnect(toolId);
|
|
21
|
+
return { status: 200, body: { ok: true, tool: { ...result.tool, type: result.tool.source.type }, actions: result.actions } };
|
|
22
|
+
}
|
|
23
|
+
if (body.status === 'enabled') {
|
|
24
|
+
const current = toolbox.get(toolId);
|
|
25
|
+
if (!current)
|
|
26
|
+
throw new Error(`Unknown tool: ${toolId}`);
|
|
27
|
+
const result = await toolbox.connect({ definition: { ...current.tool, actions: current.actions } });
|
|
28
|
+
return { status: 200, body: { ok: true, tool: { ...result.tool, type: result.tool.source.type }, actions: result.actions } };
|
|
29
|
+
}
|
|
30
|
+
throw new Error('Tool status must be enabled or disabled; reconnect with a complete definition to edit it');
|
|
31
|
+
}
|
|
32
|
+
if (method === 'DELETE') {
|
|
33
|
+
await toolbox.remove(typeof body.id === 'string' ? body.id : '');
|
|
34
|
+
return { status: 200, body: { ok: true, deleted: true } };
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
if (pathname === '/toolbox/actions/call' && method === 'POST') {
|
|
38
|
+
return { status: 200, body: await toolbox.call(typeof body.id === 'string' ? body.id : '', body.input) };
|
|
39
|
+
}
|
|
40
|
+
return { status: 405, body: { error: 'method not allowed' } };
|
|
41
|
+
}
|
package/dist/http.d.ts
CHANGED
|
@@ -12,9 +12,8 @@ import type { Catalog, ToolboxOptions } from './types.js';
|
|
|
12
12
|
* - `GET /toolbox/actions?id=...` returns one action;
|
|
13
13
|
* - domain errors are JSON with status 400; unknown routes are 404.
|
|
14
14
|
*
|
|
15
|
-
* Mutation routes
|
|
16
|
-
*
|
|
17
|
-
* them approximately would turn a visible parity gap into data loss.
|
|
15
|
+
* Mutation routes consume current SDK definitions. The authenticated composing
|
|
16
|
+
* host supplies the Toolbox owner; request bodies cannot select one.
|
|
18
17
|
*/
|
|
19
18
|
type Json = Record<string, unknown>;
|
|
20
19
|
interface ToolboxHttpServer {
|
package/dist/http.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { createServer } from 'node:http';
|
|
2
2
|
import { toolboxIndexDocument } from './artifacts.js';
|
|
3
3
|
import { Toolbox } from './toolbox.js';
|
|
4
|
+
import { mutateToolbox } from './http-mutations.js';
|
|
4
5
|
function sourceWithoutType(source) {
|
|
5
6
|
const { type: _type, ...value } = source;
|
|
6
7
|
return value;
|
|
@@ -25,8 +26,13 @@ function catalogDocument(catalog) {
|
|
|
25
26
|
}
|
|
26
27
|
async function readBody(req) {
|
|
27
28
|
const chunks = [];
|
|
28
|
-
|
|
29
|
+
let size = 0;
|
|
30
|
+
for await (const chunk of req) {
|
|
31
|
+
size += Buffer.byteLength(chunk);
|
|
32
|
+
if (size > 2 * 1024 * 1024)
|
|
33
|
+
throw new Error('Toolbox request exceeds 2 MiB');
|
|
29
34
|
chunks.push(Buffer.from(chunk));
|
|
35
|
+
}
|
|
30
36
|
if (chunks.length === 0)
|
|
31
37
|
return {};
|
|
32
38
|
return JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
@@ -45,8 +51,8 @@ function createToolboxHttpServer(options = {}) {
|
|
|
45
51
|
try {
|
|
46
52
|
if (method !== 'GET') {
|
|
47
53
|
if (url.pathname.startsWith('/toolbox')) {
|
|
48
|
-
await readBody(req);
|
|
49
|
-
send(
|
|
54
|
+
const result = await mutateToolbox(toolbox, method, url.pathname, await readBody(req));
|
|
55
|
+
send(result.status, result.body);
|
|
50
56
|
return;
|
|
51
57
|
}
|
|
52
58
|
send(404, { error: 'not found' });
|
package/dist/ids.d.ts
CHANGED
|
@@ -3,5 +3,7 @@ declare function id(value: unknown, label?: string, maximumLength?: number): str
|
|
|
3
3
|
declare function actionName(value: unknown): string;
|
|
4
4
|
declare function actionId(toolId: string, name: string): string;
|
|
5
5
|
declare function mcpName(action: Pick<ActionRecord, 'id'>): string;
|
|
6
|
+
/** Action tools carry the double-underscore prefix; management tools never do. */
|
|
7
|
+
declare function isActionMcpName(name: string): boolean;
|
|
6
8
|
declare function assertMcpNamesUnique(actions: Pick<ActionRecord, 'id'>[]): void;
|
|
7
|
-
export { actionId, actionName, assertMcpNamesUnique, id, mcpName };
|
|
9
|
+
export { actionId, actionName, assertMcpNamesUnique, id, isActionMcpName, mcpName };
|
package/dist/ids.js
CHANGED
|
@@ -21,8 +21,13 @@ function actionId(toolId, name) {
|
|
|
21
21
|
function safeMcpName(value) {
|
|
22
22
|
return value.replace(/[^A-Za-z0-9_-]+/g, '_').replace(/_+/g, '_');
|
|
23
23
|
}
|
|
24
|
+
const MCP_ACTION_PREFIX = 'toolbox__';
|
|
24
25
|
function mcpName(action) {
|
|
25
|
-
return
|
|
26
|
+
return `${MCP_ACTION_PREFIX}${safeMcpName(action.id)}`;
|
|
27
|
+
}
|
|
28
|
+
/** Action tools carry the double-underscore prefix; management tools never do. */
|
|
29
|
+
function isActionMcpName(name) {
|
|
30
|
+
return name.startsWith(MCP_ACTION_PREFIX);
|
|
26
31
|
}
|
|
27
32
|
function assertMcpNamesUnique(actions) {
|
|
28
33
|
const names = new Map();
|
|
@@ -35,4 +40,4 @@ function assertMcpNamesUnique(actions) {
|
|
|
35
40
|
names.set(name, action.id);
|
|
36
41
|
}
|
|
37
42
|
}
|
|
38
|
-
export { actionId, actionName, assertMcpNamesUnique, id, mcpName };
|
|
43
|
+
export { actionId, actionName, assertMcpNamesUnique, id, isActionMcpName, mcpName };
|