clay-server 5.6.0 → 5.7.0-beta.1
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/lib/clay-product-control.js +2 -1
- package/lib/daemon.js +12 -0
- package/lib/mcp-agent-management.js +98 -0
- package/lib/mcp-agent-tools.js +4 -3
- package/lib/mcp-local-configuration.js +20 -0
- package/lib/mcp-management-service.js +96 -0
- package/lib/mcp-remote-connections.js +127 -35
- package/lib/mcp-settings-navigation.js +34 -0
- package/lib/mcp-xcode.js +43 -0
- package/lib/project-admin-overview.js +2 -2
- package/lib/project-mcp.js +28 -6
- package/lib/project-ownership-diagnostics.js +37 -0
- package/lib/project-ownership-recovery.js +59 -0
- package/lib/project-ownership.js +1 -34
- package/lib/public/app.js +3 -0
- package/lib/public/css/mcp-connections.css +15 -0
- package/lib/public/css/mcp-skills-workbench.css +6 -4
- package/lib/public/css/project-admin-overview.css +4 -0
- package/lib/public/css/project-settings-modal.css +8 -0
- package/lib/public/css/settings-shell.css +42 -0
- package/lib/public/index.html +4 -4
- package/lib/public/modules/clay-tool-presentation.js +7 -0
- package/lib/public/modules/extension-settings.js +1 -1
- package/lib/public/modules/mcp-connection-view.js +52 -24
- package/lib/public/modules/mcp-skills-workbench.js +10 -3
- package/lib/public/modules/mcp-ui.js +40 -11
- package/lib/public/modules/mcp-xcode-view.js +42 -0
- package/lib/public/modules/project-admin-overview.js +9 -0
- package/lib/public/modules/project-ownership-recovery.js +56 -0
- package/lib/public/modules/project-session-visibility-settings.js +1 -1
- package/lib/public/modules/project-settings-access.js +91 -0
- package/lib/public/modules/project-settings-environment.js +3 -2
- package/lib/public/modules/project-settings.js +39 -5
- package/lib/public/modules/settings-project-tree.js +74 -0
- package/lib/public/modules/settings-shell-view.js +3 -1
- package/lib/public/modules/settings-shell.js +3 -2
- package/lib/public/pane-assets/{app-QR6W64PK.js → app-KYK2HXZR.js} +1 -1
- package/lib/public/pane-assets/chunk-3CGVMON5.js +1 -0
- package/lib/public/pane-assets/{chunk-YDQZXMHJ.js → chunk-3WQWIQ53.js} +1 -1
- package/lib/public/pane-assets/{chunk-I5RM7KNO.js → chunk-42POZKMA.js} +1 -1
- package/lib/public/pane-assets/chunk-53PJD7FQ.js +1 -0
- package/lib/public/pane-assets/{chunk-HXD34AZT.js → chunk-5525OCE4.js} +1 -1
- package/lib/public/pane-assets/{chunk-K3AFWB4T.js → chunk-6WHHBK62.js} +100 -100
- package/lib/public/pane-assets/{chunk-H6RI6IG5.js → chunk-7DMFCL3J.js} +1 -1
- package/lib/public/pane-assets/chunk-7IDJFDUF.js +1 -0
- package/lib/public/pane-assets/chunk-C4BC5QKM.js +1 -0
- package/lib/public/pane-assets/{chunk-OHKQX2VV.js → chunk-G2OD6CYE.js} +1 -1
- package/lib/public/pane-assets/{chunk-TUZOISN6.js → chunk-H2Z5IANY.js} +1 -1
- package/lib/public/pane-assets/{chunk-4KCNVBBD.js → chunk-I74MAWWL.js} +1 -1
- package/lib/public/pane-assets/{chunk-UBGZO6GV.js → chunk-IPEGITRJ.js} +1 -1
- package/lib/public/pane-assets/{chunk-25X3V6RW.js → chunk-NTWCEBHU.js} +1 -1
- package/lib/public/pane-assets/{chunk-KLRVHJC5.js → chunk-NZYCUCTU.js} +1 -1
- package/lib/public/pane-assets/chunk-OX66WEZB.js +1 -0
- package/lib/public/pane-assets/{chunk-WI7YYJ5R.js → chunk-SDEVOBXA.js} +1 -1
- package/lib/public/pane-assets/chunk-TA6KA3QG.js +1 -0
- package/lib/public/pane-assets/chunk-TDKHZ2NU.js +1 -0
- package/lib/public/pane-assets/{chunk-H3BOT3SB.js → chunk-UEQM5YNB.js} +1 -1
- package/lib/public/pane-assets/{chunk-IIZZTDLB.js → chunk-WBLXJD4Q.js} +1 -1
- package/lib/public/pane-assets/{chunk-TKD25TLY.js → chunk-YZAEN74U.js} +1 -1
- package/lib/public/pane-assets/chunk-ZBCR4WTM.js +1 -0
- package/lib/public/pane-assets/manifest.json +416 -412
- package/lib/public/pane-assets/style-WRLOVB6B.css +1 -0
- package/lib/server-project-ownership.js +39 -0
- package/lib/server.js +5 -0
- package/package.json +1 -1
- package/lib/public/pane-assets/chunk-AKFJO7SA.js +0 -1
- package/lib/public/pane-assets/chunk-DX7R6GRL.js +0 -1
- package/lib/public/pane-assets/chunk-F33TBKP2.js +0 -1
- package/lib/public/pane-assets/chunk-PTZ2QTNA.js +0 -1
- package/lib/public/pane-assets/chunk-QWNMLSVA.js +0 -1
- package/lib/public/pane-assets/chunk-VG32EEIQ.js +0 -1
- package/lib/public/pane-assets/chunk-W2W4CPO7.js +0 -1
- package/lib/public/pane-assets/chunk-XX2GY7T5.js +0 -1
- package/lib/public/pane-assets/style-BCUGGAD3.css +0 -1
|
@@ -83,7 +83,8 @@ function attachClayProductControl(ctx) {
|
|
|
83
83
|
return { screen: { tools: ["read_owner_screen", "inspect_owner_screen_change", "control_owner_screen"], scope: "Exact authenticated owner UI connection and owned conversation navigation; delivery and client acceptance do not prove rendering. screen_context lists server-known connections. split_views reads saved configuration and challenges one selected live project window for visible/cached pane bindings, layout and focus. Typed reviewed split_view changes share human persistence and navigation paths. Owner notification read and reviewed exact dismissal use the existing queue. No arbitrary messages or Settings. Split view create/update/rename/separate/member transfer/folder/Favorite/open/focus are supported in the selected live project window; zero-to-eight session composition and bounded v1 workspace updates for existing tool instances share the human View service. File Follow/Pin/close, placement and layout are supported; new or rebound tool resources remain unavailable through this control. Saved descriptors and client observations are distinct. Account-wide workbench mode remains excluded.", receipts: "Query-local attempts survive catalog rebinding only. Read delivery status; never blindly repeat an uncertain delivery." }, actions: ACTIONS, scheduling: { tools: ["begin_schedule_control_interview", "read_schedule_controls", "inspect_schedule_change", "control_schedules"], mates: "Own and same-owner private Mate conversation list/read/create/update/cancel. No pause/resume/run-now action exists for logical Mate schedules.", projects: "Selected owned ordinary-project Driver list/read, proposed creation requiring final workbench Create task, reviewed update/pause/resume/cancel/run through existing scheduling services. Run is queued, never task completion; Workers remain owned by the project scheduled executor.", receipts: "Dated request IDs; 24-hour receipt window, at most 100 retained receipts on the source conversation. Interrupted writes require inspection, never blind execution." }, projectRecords: { tools: ["read_project_records", "inspect_project_record_change", "control_project_records"], scope: "Selected owned ordinary projects, including worktree context. Exact owner review; query-local bounded retry receipts.", unsupported: ["githubFiling", "workSessionLaunch", "scheduledResultMutation"], routing: "Use the existing reviewed project assignment or follow-up tools for Driver execution. Record changes never run Git commits." }, mateKnowledge: { tools: ["read_mate_knowledge_control", "inspect_mate_knowledge_change", "control_mate_knowledge"], review: "Exact owner-reviewed Markdown and typed database/record operations; serialized intents are limited to 1400 characters within the existing review card.", unsupported: ["hardDatabaseOrRecordDeletion", "legacyJsonlWrites", "promotionOrSharing", "arbitraryFilesystemOrSql", "userKnowledgeCuration"] }, mateLifecycle: { actions: ["list", "inspect", "profile", "delete"], profileFields: ["name", "bio", "workspaceColor", "avatarCatalogId"], deletion: "Idle owner-private Mates only; canonical Clay and primary Mates are protected. Stored transcripts and provider history are retained. Pending runtime cleanup without closure proof requires operator recovery.", excluded: ["knowledge", "directMessages", "schedules", "sharing", "ownershipTransfer", "model"] }, mateChat: { tools: ["read_mate_chat_control", "inspect_mate_chat_change", "control_mate_chat"], actions: ["send", "stop", "model", "vendor", "effort"], scope: "Exact existing same-owner private Mate conversation; vendor selection requires a fresh idle conversation. Delegated messages are untrusted and never owner input. Dated durable retry receipts, no implicit resume or thread migration." }, workspace: { tools: ["read_project_workspace", "read_workspace_receipt", "inspect_workspace_change", "control_project_workspace"], files: "Bounded list/read and exact reviewed writes to existing regular text files within a selected owned ordinary project. Symlinks, hardlinks, managed settings, create/delete/move and arbitrary filesystem operations are excluded.", git: "Status and changed-file diff; exact reviewed selected-path stage/unstage only. No linked Git metadata/submodules, commits, pull/push, PR operations or arbitrary Git arguments.", terminal: "Owner shell list/scrollback and reviewed blank shell creation, rename, resize and acknowledged close. No input, commands, coding-agent/login terminals or Worker control." }, approval: "All changes except Stop require an authenticated owner review of the exact action and target revision.",
|
|
84
84
|
vendorUsage: { tools: ["read_vendor_usage"], scope: "Read-only usage of the owner's own vendor accounts and sessions in one owned project, through the same service as the top bar; the owner's identity only, no refresh, credentials, URLs, commands or settings. Account figures keep each vendor's units; unreadable usage is reported with its reason." },
|
|
85
85
|
taskExecution: "Use propose_project_assignment or propose_project_follow_up to route execution through a project Driver. A stopped session cannot be resumed by this control layer.",
|
|
86
|
-
|
|
86
|
+
mcp: { tools: ['read_mcp_connections', 'inspect_mcp_connection_change', 'apply_mcp_connection_change', 'discover_mcp_connections', 'propose_mcp_import'], scope: 'Owner-private agent MCP catalog shared with supported Drivers and Mates. Read connections/tools and bounded Xcode readiness; exact owner-reviewed local/remote add, enable/disable, test, rename/remove, sign-in start, Xcode connect/disconnect and Client MCP toggles. Same authoritative services as human MCP management. Secure credential/token/permission forms and Client setup can be requested on the exact approving interface, with changed-context refusal and explicit client acknowledgement; acceptance does not prove visible rendering. Credentials are never accepted in agent arguments. Extension/bridge installation, extension server definitions, Xcode settings/license and direct session approval policy changes remain human steps. No general Server Settings or User Settings dispatch.', receipts: 'At most 100 per source query, ten-minute expiry, no automatic replay, no durable receipt after restart.' },
|
|
87
|
+
unsupported: { projectOwnershipRecovery: "Human administrator-only diagnosis and reviewed recovery in Project settings or the restricted project Access page. Orphan projects have no verified owner to authorize canonical project controls; canonical Clay cannot inspect or claim them. Server operator identity provisioning remains manual.", personalProviders: "Personal AI provider installation discovery, reviewed supported installation, sign-in and audio transcription API keys are available only in authenticated human settings. No canonical credential, provider installation or sign-in operation is exposed.", worktrees: "Worktree icon edits, exclusion and disk deletion are available only through human product controls. Restoring exclusions and reconciling pending worktree removals have no in-app operation.", archive: "No authoritative session archive service exists.", send: "Use reviewed Driver assignment or follow-up.", runtime: "New TUI presentation and cross-provider thread migration are unavailable. runtime=gui closes a legacy Claude terminal with acknowledged exit. vendor_new_session creates a private blank GUI session and retains the original without execution.", projectLifecycle: ctx.projectLifecycle ? "Create, register, rename, remove registration, project environment and owner access controls use exact human review. OS filesystem sharing changes are unavailable through this service." : "Unavailable in this runtime." },
|
|
87
88
|
excluded: ["serverSettings", "userSettings", "workerCreation", "pairOrchestration"] };
|
|
88
89
|
}
|
|
89
90
|
function inspect(args) {
|
package/lib/daemon.js
CHANGED
|
@@ -200,7 +200,19 @@ var worktreeControls = require("./daemon-worktree-controls").attachWorktreeContr
|
|
|
200
200
|
getRelay: function () { return relay; }, findUser: usersModule.findUserById, users: usersModule,
|
|
201
201
|
osIdentity: worktreeOsUserInfo, syncRecent: syncClayrc, storageDir: require("./config").CONFIG_DIR, unregister: unregisterWorktreeSlug,
|
|
202
202
|
});
|
|
203
|
+
var ownershipRecovery = require('./project-ownership-recovery').createRecoveryService({
|
|
204
|
+
getConfig: function () { return config; }, getAccounts: usersModule.getAllUsers,
|
|
205
|
+
resolveIdentity: osUsersMod.resolveOsUserInfo, persist: saveConfig,
|
|
206
|
+
publish: function (next, slug, ownerId) {
|
|
207
|
+
relay.forEachProject(function (project, projectSlug) {
|
|
208
|
+
if (projectSlug === slug || daemonProjectAccess.parentSlugFor(projectSlug) === slug) project.setProjectOwner(ownerId);
|
|
209
|
+
});
|
|
210
|
+
config = next;
|
|
211
|
+
relay.refreshProjectAccess();
|
|
212
|
+
}
|
|
213
|
+
});
|
|
203
214
|
var relay = createServer({
|
|
215
|
+
ownershipRecovery: ownershipRecovery,
|
|
204
216
|
worktreeControls: worktreeControls,
|
|
205
217
|
projectLifecycle: projectLifecycle,
|
|
206
218
|
tlsOptions: tlsOptions,
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
var crypto = require('crypto');
|
|
2
|
+
var userInput = require('./yoke/user-input');
|
|
3
|
+
var actions = require('./mcp-management-service').ACTIONS;
|
|
4
|
+
var TTL = 10 * 60 * 1000;
|
|
5
|
+
function result(value, error) { return { content: [{ type: 'text', text: JSON.stringify(value) }], isError: !!error }; }
|
|
6
|
+
function attachManagementTools(ctx) {
|
|
7
|
+
var sessions = new WeakMap(), active = new Set(), closed = false;
|
|
8
|
+
function state(session, generation) {
|
|
9
|
+
var value = sessions.get(session);
|
|
10
|
+
if (!value || value.generation !== generation) { value = { generation: generation, receipts: new Map() }; sessions.set(session, value); }
|
|
11
|
+
value.receipts.forEach(function (entry, key) { if (entry.expires <= Date.now()) value.receipts.delete(key); });
|
|
12
|
+
return value;
|
|
13
|
+
}
|
|
14
|
+
function definitions(session, owner, generation, authorize) {
|
|
15
|
+
var sourceOrigin = session.sessionOriginId || null;
|
|
16
|
+
if (session.spawn || session.delegated || session._delegatedBy || session._pairDelegation || session.sessionProvenance && session.sessionProvenance.kind === 'worker') return [];
|
|
17
|
+
function check() {
|
|
18
|
+
authorize();
|
|
19
|
+
if ((session.sessionOriginId || null) !== sourceOrigin) throw new Error('MCP source conversation changed.');
|
|
20
|
+
if (closed || session.spawn || session.delegated || session._delegatedBy || session._pairDelegation || session._mentionInProgress || session.homeDebatePlanning || session.sessionProvenance && session.sessionProvenance.kind === 'worker') throw new Error('MCP management requires a direct owner-private agent conversation.');
|
|
21
|
+
}
|
|
22
|
+
function receipt(id) {
|
|
23
|
+
var entry = state(session, generation).receipts.get(id);
|
|
24
|
+
if (!entry) throw new Error('MCP review receipt expired or belongs to another query. Inspect a new change; do not replay an uncertain effect.');
|
|
25
|
+
return entry;
|
|
26
|
+
}
|
|
27
|
+
async function read(args) {
|
|
28
|
+
check();
|
|
29
|
+
if (args.changeId !== undefined) {
|
|
30
|
+
if (Object.keys(args).length !== 1) throw new Error('Read a change receipt by changeId only.');
|
|
31
|
+
var entry = receipt(args.changeId);
|
|
32
|
+
return result({ changeId: args.changeId, status: entry.status, result: entry.output || null, expiresAt: entry.expires, lifetime: 'Source query only, at most ten minutes; no durable retry after restart.' });
|
|
33
|
+
}
|
|
34
|
+
return result(await ctx.service.read(owner, args, check));
|
|
35
|
+
}
|
|
36
|
+
function inspect(args) {
|
|
37
|
+
check(); var current = state(session, generation);
|
|
38
|
+
if (current.receipts.size >= 100) throw new Error('This query reached the MCP review limit. Read existing receipts before continuing.');
|
|
39
|
+
var plan = ctx.service.prepare(owner, args, session, check), id = 'mcp-change-' + crypto.randomUUID();
|
|
40
|
+
var entry = { plan: plan, status: 'inspected', expires: Date.now() + TTL };
|
|
41
|
+
current.receipts.set(id, entry);
|
|
42
|
+
return result({ status: 'inspected', changeId: id, review: plan.review, expiresAt: entry.expires, applied: false });
|
|
43
|
+
}
|
|
44
|
+
async function apply(args) {
|
|
45
|
+
check();
|
|
46
|
+
if (Object.keys(args).length !== 1 || typeof args.changeId !== 'string') throw new Error('Pass only the exact changeId. Agent-provided approval is never accepted.');
|
|
47
|
+
var entry = receipt(args.changeId);
|
|
48
|
+
if (entry.status !== 'inspected') return result({ changeId: args.changeId, status: entry.status, result: entry.output || null, replayed: false });
|
|
49
|
+
if (!ctx.humans(session, owner) || session.loop && session.loop.active && session.loop.role !== 'crafting') return result({ status: 'consent_unavailable', applied: false, message: 'The authenticated owner must open this conversation to review the exact MCP change.' });
|
|
50
|
+
var controller = new AbortController(), reviewer = null, timer, expired = false;
|
|
51
|
+
var sourceSignal = session.abortController && session.abortController.signal;
|
|
52
|
+
function stopped() { controller.abort(); }
|
|
53
|
+
function live() { check(); if (controller.signal.aborted || Date.now() >= entry.expires || !reviewer || !ctx.canRespond(reviewer, session, owner)) throw new Error('MCP review stopped, expired or owner disconnected.'); }
|
|
54
|
+
entry.status = 'reviewing'; active.add(controller);
|
|
55
|
+
if (sourceSignal) sourceSignal.addEventListener('abort', stopped, { once: true });
|
|
56
|
+
try {
|
|
57
|
+
timer = setTimeout(function () { expired = true; controller.abort(); }, Math.min(ctx.consentTimeout || 45000, 45000));
|
|
58
|
+
var handler = ctx.userInput && ctx.userInput(session);
|
|
59
|
+
var answer = await userInput.dispatchUserInput(function (request, respond) {
|
|
60
|
+
request.authorizeResponse = function (ws) {
|
|
61
|
+
try { check(); if (controller.signal.aborted || entry.status !== 'reviewing' || !ctx.canRespond(ws, session, owner)) return false; reviewer = ws; return true; } catch (error) { return false; }
|
|
62
|
+
};
|
|
63
|
+
if (typeof handler !== 'function') return respond.cancel('Owner review is unavailable.');
|
|
64
|
+
return handler(request, respond);
|
|
65
|
+
}, { questions: [{ id: 'mcp_change', header: 'MCP change', question: entry.plan.review, allowOther: false, options: [{ label: 'Keep unchanged' }, { label: 'Apply this MCP change' }] }] }, { source: 'product-control', requestId: 'mcp_change_' + crypto.randomUUID(), signal: controller.signal });
|
|
66
|
+
clearTimeout(timer);
|
|
67
|
+
if (answer.status !== 'submitted' || !answer.answers.mcp_change || answer.answers.mcp_change.length !== 1 || answer.answers.mcp_change[0] !== 'Apply this MCP change') {
|
|
68
|
+
entry.status = expired ? 'expired' : answer.status === 'submitted' ? 'declined' : answer.status;
|
|
69
|
+
return result({ status: entry.status, applied: false, changeId: args.changeId });
|
|
70
|
+
}
|
|
71
|
+
live();
|
|
72
|
+
if (ctx.service.version(owner) !== entry.plan.version) throw new Error('MCP connections changed. Inspect a new change.');
|
|
73
|
+
entry.plan.validate();
|
|
74
|
+
timer = setTimeout(stopped, Math.max(1, entry.expires - Date.now()));
|
|
75
|
+
entry.status = 'queued';
|
|
76
|
+
entry.output = await entry.plan.execute(reviewer, controller.signal, function () { entry.status = 'started'; });
|
|
77
|
+
live(); entry.status = entry.output.status;
|
|
78
|
+
return result(Object.assign({ changeId: args.changeId }, entry.output));
|
|
79
|
+
} catch (error) {
|
|
80
|
+
entry.output = { message: error.message, inspectBeforeRetry: true };
|
|
81
|
+
entry.status = entry.status === 'started' ? 'unknown' : 'refused';
|
|
82
|
+
return result({ status: entry.status, changeId: args.changeId, result: entry.output }, true);
|
|
83
|
+
} finally {
|
|
84
|
+
function cleanup() { clearTimeout(timer); active.delete(controller); if (sourceSignal) sourceSignal.removeEventListener('abort', stopped); }
|
|
85
|
+
if (entry.status === 'sign_in_started' && !controller.signal.aborted) controller.signal.addEventListener('abort', cleanup, { once: true });
|
|
86
|
+
else cleanup();
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
function wrap(handler) { return function (args) { return Promise.resolve().then(function () { return handler(args || {}); }).catch(function (error) { return result({ status: 'refused', message: error.message }, true); }); }; }
|
|
90
|
+
return [
|
|
91
|
+
{ name: 'read_mcp_connections', description: 'Read your own Local, Remote and Client MCP connections, paginated tool details, or an exact change receipt. checkXcode performs a bounded read-only host readiness check. Never returns stored credentials. Read humanSteps for setup that still needs a person.', inputSchema: { type: 'object', properties: { id: { type: 'string' }, changeId: { type: 'string' }, checkXcode: { type: 'boolean' }, offset: { type: 'integer', minimum: 0 }, limit: { type: 'integer', minimum: 1, maximum: 100 } }, additionalProperties: false }, handler: wrap(read) },
|
|
92
|
+
{ name: 'inspect_mcp_connection_change', description: 'Prepare one exact MCP setup/change for authenticated owner review without applying it. Supports local/remote add, enable/disable, test, rename/remove, private browser sign-in, Xcode connect/disconnect, Client MCP toggles/setup and opening secure credential/token/permission forms. Never put credentials in arguments, URLs or chat. Use existing import discovery/proposal tools for vendor import.', inputSchema: { type: 'object', properties: { action: { type: 'string', enum: actions }, id: { type: 'string' }, label: { type: 'string', maxLength: 100 }, command: { type: 'string', maxLength: 4096 }, args: { type: 'array', items: { type: 'string' }, maxItems: 100 }, cwd: { type: 'string', maxLength: 4096 }, url: { type: 'string', maxLength: 4096 } }, required: ['action'], additionalProperties: false }, handler: wrap(inspect) },
|
|
93
|
+
{ name: 'apply_mcp_connection_change', description: 'Show the exact prepared MCP change to the authenticated owner and apply only after that owner approves. Pass only changeId; model approval flags and delegated answers are rejected. Receipts last at most ten minutes in this source query; repeating an ID reads its status and never replays an effect. Stop cancels further work; unknown outcomes require inspection. Opening a form is not credential persistence; starting sign-in is not authentication.', inputSchema: { type: 'object', properties: { changeId: { type: 'string' } }, required: ['changeId'], additionalProperties: false }, handler: wrap(apply) },
|
|
94
|
+
];
|
|
95
|
+
}
|
|
96
|
+
return { definitions: definitions, destroy: function () { closed = true; active.forEach(function (controller) { controller.abort(); }); active.clear(); sessions = new WeakMap(); } };
|
|
97
|
+
}
|
|
98
|
+
module.exports = { attachManagementTools: attachManagementTools };
|
package/lib/mcp-agent-tools.js
CHANGED
|
@@ -44,6 +44,7 @@ function attachMcpAgentTools(ctx) {
|
|
|
44
44
|
if (question.length > 2000) throw new Error('This candidate needs a larger policy review than the consent card supports. Review it in MCP management; no import was made.');
|
|
45
45
|
return question;
|
|
46
46
|
}
|
|
47
|
+
var management = ctx.management && require('./mcp-agent-management').attachManagementTools({ service: ctx.management, humans: humans, canRespond: canRespond, userInput: ctx.userInput, consentTimeout: ctx.consentTimeout });
|
|
47
48
|
function definitions(session) {
|
|
48
49
|
var owner = ownerOf(session), generation = Number(session._sdkQueryGeneration || 0);
|
|
49
50
|
function authorize() { authorized(session, owner, generation); }
|
|
@@ -101,7 +102,7 @@ function attachMcpAgentTools(ctx) {
|
|
|
101
102
|
}
|
|
102
103
|
function wrap(handler) { return function (args) { return Promise.resolve().then(function () { return handler(args || {}); }).catch(function (error) { return result({ status: 'refused', imported: false, message: error.message }, true); }); }; }
|
|
103
104
|
return [{ name: 'discover_mcp_connections', description: 'Read-only inspection of your vendor MCP sources. Returns redacted candidate IDs and provenance. Never executes commands, imports, activates, logs in or reads vendor OAuth stores. Use credential entry only in MCP management.', inputSchema: { type: 'object', properties: { vendor: { type: 'string' }, file: { type: 'string' } }, additionalProperties: false }, handler: wrap(discover) },
|
|
104
|
-
{ name: 'propose_mcp_import', description: 'Present one exact discovered candidate to the authenticated owner for structured approval, then save a disabled copy only after explicit approval. Denial, cancellation, timeout or absent owner causes no import. Pass only scanId and candidateId; agent-provided approval is never accepted.', inputSchema: { type: 'object', properties: { scanId: { type: 'string' }, candidateId: { type: 'string' } }, required: ['scanId', 'candidateId'], additionalProperties: false }, handler: wrap(propose) }];
|
|
105
|
+
{ name: 'propose_mcp_import', description: 'Present one exact discovered candidate to the authenticated owner for structured approval, then save a disabled copy only after explicit approval. Denial, cancellation, timeout or absent owner causes no import. Pass only scanId and candidateId; agent-provided approval is never accepted.', inputSchema: { type: 'object', properties: { scanId: { type: 'string' }, candidateId: { type: 'string' } }, required: ['scanId', 'candidateId'], additionalProperties: false }, handler: wrap(propose) }].concat(management ? management.definitions(session, owner, generation, authorize) : []);
|
|
105
106
|
}
|
|
106
107
|
function getServer(session) {
|
|
107
108
|
try {
|
|
@@ -111,7 +112,7 @@ function attachMcpAgentTools(ctx) {
|
|
|
111
112
|
return createProxy(SERVER, tools, function (name, args) { var tool = tools.find(function (item) { return item.name === name; }); return tool.handler(args); });
|
|
112
113
|
} catch (error) { return null; }
|
|
113
114
|
}
|
|
114
|
-
function destroy() { closed = true; pending.forEach(function (entry) { entry.controller.abort(); }); pending.clear(); used = new WeakMap(); viewers.clear(); }
|
|
115
|
-
return { getServer: getServer, registerViewer: registerViewer, destroy: destroy };
|
|
115
|
+
function destroy() { if (management) management.destroy(); closed = true; pending.forEach(function (entry) { entry.controller.abort(); }); pending.clear(); used = new WeakMap(); viewers.clear(); }
|
|
116
|
+
return { getServer: getServer, registerViewer: registerViewer, canRespond: canRespond, canViewOwner: function (ws, owner) { var listed = viewers.get(ws); return !!listed && Array.from(listed.keys()).some(function (session) { return canRespond(ws, session, owner) && ctx.canUseSession(session); }); }, destroy: destroy };
|
|
116
117
|
}
|
|
117
118
|
module.exports = { attachMcpAgentTools: attachMcpAgentTools, SERVER: SERVER };
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
var path = require('path');
|
|
2
|
+
var os = require('os');
|
|
3
|
+
var normalize = require('./yoke/mcp-source-adapters').normalize;
|
|
4
|
+
|
|
5
|
+
function configuration(msg, identity) {
|
|
6
|
+
if (typeof msg.label !== 'string' || !msg.label.trim() || msg.label.length > 100 || /[\u0000-\u001f]/.test(msg.label)) throw new Error('Use a name between 1 and 100 characters.');
|
|
7
|
+
if (typeof msg.command !== 'string' || !msg.command.trim() || msg.command.length > 4096 || /[\u0000-\u001f]/.test(msg.command)) throw new Error('Enter an executable command without shell syntax.');
|
|
8
|
+
if (typeof msg.argumentsJson !== 'string' || msg.argumentsJson.length > 16384) throw new Error('Enter arguments as a JSON array of strings.');
|
|
9
|
+
var args;
|
|
10
|
+
try { args = JSON.parse(msg.argumentsJson); } catch (error) { throw new Error('Enter arguments as a JSON array of strings, for example ["-y", "your-mcp-package"].'); }
|
|
11
|
+
if (!Array.isArray(args) || args.length > 100 || args.some(function (value) { return typeof value !== 'string' || value.includes('\0'); })) throw new Error('Enter at most 100 string arguments in a JSON array.');
|
|
12
|
+
if (msg.cwd !== undefined && (typeof msg.cwd !== 'string' || msg.cwd.length > 4096 || /[\u0000-\u001f]/.test(msg.cwd))) throw new Error('Use an absolute working directory.');
|
|
13
|
+
var cwd = msg.cwd && msg.cwd.trim() || (identity ? identity.home : os.homedir());
|
|
14
|
+
if (!cwd || !path.isAbsolute(cwd)) throw new Error('Use an absolute working directory.');
|
|
15
|
+
var config = normalize('claude', msg.label.trim(), { command: msg.command.trim(), args: args, cwd: cwd }, { scope: 'user', cwd: cwd });
|
|
16
|
+
delete config.provenance; delete config.sourceEnabled;
|
|
17
|
+
config.tools = [];
|
|
18
|
+
return config;
|
|
19
|
+
}
|
|
20
|
+
module.exports = { configuration: configuration };
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
var crypto = require('crypto');
|
|
2
|
+
var local = require('./mcp-local-configuration');
|
|
3
|
+
var network = require('./mcp-network');
|
|
4
|
+
var ACTIONS = ['add_local', 'add_remote', 'enable', 'disable', 'test', 'rename', 'remove', 'signin', 'xcode_connect', 'xcode_disconnect', 'client_enable', 'client_disable', 'client_setup', 'enter_credentials', 'enter_token', 'permissions'];
|
|
5
|
+
function exact(args, keys) {
|
|
6
|
+
if (!args || typeof args !== 'object' || Array.isArray(args) || Object.keys(args).some(function (key) { return keys.indexOf(key) < 0; })) throw new Error('Unsupported MCP management input.');
|
|
7
|
+
}
|
|
8
|
+
function name(value, field, max) {
|
|
9
|
+
if (typeof value !== 'string' || !value.trim() || value.length > max || /[\u0000-\u001f\u007f]/.test(value)) throw new Error('Enter a valid ' + field + '.');
|
|
10
|
+
return value.trim();
|
|
11
|
+
}
|
|
12
|
+
function createManagementService(ctx) {
|
|
13
|
+
function version(owner) {
|
|
14
|
+
return crypto.createHash('sha256').update(JSON.stringify([ctx.remote.managementVersion(owner), ctx.clientVersion(owner)])).digest('hex');
|
|
15
|
+
}
|
|
16
|
+
async function read(owner, args, authorize) {
|
|
17
|
+
exact(args, ['id', 'checkXcode', 'offset', 'limit']); authorize();
|
|
18
|
+
if (args.checkXcode !== undefined && typeof args.checkXcode !== 'boolean') throw new Error('Invalid Xcode check flag.');
|
|
19
|
+
if (args.checkXcode) await ctx.remote.inspectXcode(owner, authorize);
|
|
20
|
+
authorize();
|
|
21
|
+
var state = ctx.state(owner), rows = state.servers;
|
|
22
|
+
var output = { status: 'observed', revision: version(owner), extensionConnected: state.extensionConnected, bridgeConnected: state.hostConnected, xcode: state.xcode,
|
|
23
|
+
setup: ['Local MCP', 'Remote MCP URL', 'Import vendor config', 'Client MCP'],
|
|
24
|
+
humanSteps: ['Enter access tokens and credential values only in the MCP settings form.', 'Extension installation, bridge installation, extension server definitions and Xcode settings are human setup operations.', 'Permissions opens the existing session policy editor; this tool does not change session approval policy.'] };
|
|
25
|
+
if (args.id !== undefined) {
|
|
26
|
+
var id = name(args.id, 'connection ID', 300), row = rows.find(function (item) { return item.id === id; });
|
|
27
|
+
if (!row) throw new Error('Connection is unavailable.');
|
|
28
|
+
var offset = args.offset === undefined ? 0 : args.offset, limit = args.limit === undefined ? 50 : args.limit;
|
|
29
|
+
if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(limit) || limit < 1 || limit > 100) throw new Error('Use a non-negative offset and a limit from 1 to 100.');
|
|
30
|
+
output.connection = Object.assign({}, row, { tools: (row.tools || []).slice(offset, offset + limit) });
|
|
31
|
+
output.nextOffset = offset + limit < (row.tools || []).length ? offset + limit : null;
|
|
32
|
+
} else output.connections = rows.map(function (row) { var result = Object.assign({}, row); delete result.tools; return result; });
|
|
33
|
+
return output;
|
|
34
|
+
}
|
|
35
|
+
function prepare(owner, args, session, authorize) {
|
|
36
|
+
authorize();
|
|
37
|
+
var action = args.action;
|
|
38
|
+
if (ACTIONS.indexOf(action) < 0) throw new Error('Unsupported MCP management action.');
|
|
39
|
+
var keys = ['action'], msg = {}, target, screen, title, config;
|
|
40
|
+
if (action === 'add_local') keys = keys.concat(['label', 'command', 'args', 'cwd']);
|
|
41
|
+
else if (action === 'add_remote') keys.push('url');
|
|
42
|
+
else if (['xcode_connect', 'xcode_disconnect', 'client_setup'].indexOf(action) < 0) keys.push('id');
|
|
43
|
+
if (action === 'rename') keys.push('label');
|
|
44
|
+
exact(args, keys);
|
|
45
|
+
var snapshot = version(owner), remoteVersion = ctx.remote.managementVersion(owner), identity = ctx.identityKey(owner);
|
|
46
|
+
if (keys.indexOf('id') >= 0) {
|
|
47
|
+
target = ctx.state(owner).servers.find(function (row) { return row.id === name(args.id, 'connection ID', 300); });
|
|
48
|
+
if (!target) throw new Error('Connection is unavailable.');
|
|
49
|
+
msg.id = target.id;
|
|
50
|
+
}
|
|
51
|
+
if (action === 'add_local') {
|
|
52
|
+
config = local.configuration({ label: args.label, command: args.command, argumentsJson: JSON.stringify(args.args === undefined ? [] : args.args), cwd: args.cwd }, ctx.identity(owner));
|
|
53
|
+
msg = { action: 'add_local', label: config.label, command: config.command, argumentsJson: JSON.stringify(config.args), cwd: config.cwd };
|
|
54
|
+
title = 'Save a DISABLED Local MCP connection: ' + config.label + '\nCommand: ' + config.command + '\nArguments: ' + JSON.stringify(config.args) + '\nWorking directory: ' + config.cwd + '\nNo program starts until a separate Enable or Test action.';
|
|
55
|
+
} else if (action === 'add_remote') {
|
|
56
|
+
msg = { action: 'add', url: network.remoteUrl(args.url).href };
|
|
57
|
+
title = 'Add and test remote MCP: ' + msg.url + '\nClay will contact this public HTTPS service. The saved connection starts disabled.';
|
|
58
|
+
} else if (action === 'client_setup') { screen = 'client'; title = 'Open Client MCP setup on this exact owner interface. Extension and bridge installation remain human steps.'; }
|
|
59
|
+
else if (['enter_credentials', 'enter_token', 'permissions'].includes(action)) {
|
|
60
|
+
if (target.source === 'computer' && action !== 'permissions' || target.source !== 'url' && action === 'enter_token' || action === 'enter_credentials' && !(target.references || []).length) throw new Error('This connection does not support that settings form.');
|
|
61
|
+
screen = action === 'enter_credentials' ? 'credentials' : action === 'enter_token' ? 'token' : 'permissions';
|
|
62
|
+
title = 'Open ' + screen + ' for ' + target.label + '. Enter secrets only in the existing secure settings form. Opening does not change any values.';
|
|
63
|
+
} else if (action === 'client_enable' || action === 'client_disable') {
|
|
64
|
+
if (target.source !== 'computer') throw new Error('Select an exact Client MCP connection.');
|
|
65
|
+
title = (action === 'client_enable' ? 'Enable' : 'Disable') + ' Client MCP ' + target.label + ' for this project. This changes tool availability, not approval for individual calls.';
|
|
66
|
+
} else {
|
|
67
|
+
if (target && target.source === 'computer') throw new Error('Client MCP supports project enable/disable and setup; edit its definitions in the extension.');
|
|
68
|
+
msg.action = action === 'enable' || action === 'disable' ? 'enable' : action;
|
|
69
|
+
if (msg.action === 'enable') msg.enabled = action === 'enable';
|
|
70
|
+
if (action === 'rename') msg.label = name(args.label, 'name', 100);
|
|
71
|
+
title = action.replace(/_/g, ' ') + ': ' + (target ? target.label + ' (' + target.id + ')' : 'Xcode on the Clay host');
|
|
72
|
+
if (target && target.integration === 'xcode' && action === 'enable') msg.action = 'xcode_connect';
|
|
73
|
+
if (['enable', 'test', 'xcode_connect'].includes(action)) title += '\nThis can start a program on the Clay host or contact its MCP service. Tools become available to your supported private sessions and Mates after enablement; individual calls still follow session approval policy.';
|
|
74
|
+
if (action === 'remove') title += '\nRemoves this saved connection and its stored credentials. This cannot undo earlier tool calls.';
|
|
75
|
+
if (action === 'signin') title += '\nStarts the existing private sign-in browser for the authenticated owner. The agent receives no credentials; starting sign-in is not completed authentication.';
|
|
76
|
+
}
|
|
77
|
+
var question = title + '\nAccount: ' + owner + '\nConnection revision: ' + snapshot + '\nOnly this exact action is reviewed. Stop cancels further work; uncertain effects are never replayed automatically.';
|
|
78
|
+
if (question.length > 2000) throw new Error('This change exceeds the review card limit. Use MCP settings to review its complete configuration.');
|
|
79
|
+
return { action: action, review: question, version: snapshot, validate: function () { authorize(); if (ctx.identityKey(owner) !== identity || version(owner) !== snapshot) throw new Error('MCP target or OS identity changed. Inspect again.'); }, execute: async function (ws, signal, started) {
|
|
80
|
+
function check() { authorize(); if (signal.aborted || ctx.identityKey(owner) !== identity || !ctx.canRespond(ws, session, owner)) throw new Error('MCP review expired, stopped, or owner identity changed.'); }
|
|
81
|
+
check(); if (version(owner) !== snapshot) throw new Error('MCP connections changed. Inspect the change again.');
|
|
82
|
+
if (screen) { started(); return ctx.openSettings(owner, ws, screen, target && target.id, session, check, signal); }
|
|
83
|
+
if (action === 'client_enable' || action === 'client_disable') {
|
|
84
|
+
started(); ctx.toggleClient(owner, target.name, action === 'client_enable', check); check();
|
|
85
|
+
return { status: 'persisted', id: target.id, enabled: action === 'client_enable', scope: 'project' };
|
|
86
|
+
}
|
|
87
|
+
var id = await ctx.remote.command(owner, msg, ws, { version: remoteVersion, authorize: check, signal: signal, started: started });
|
|
88
|
+
check();
|
|
89
|
+
var row = ctx.remote.view(owner).find(function (item) { return item.id === id; });
|
|
90
|
+
var status = action === 'test' ? 'tested' : action === 'signin' ? row && row.status === 'ready' ? 'connection_ready' : 'sign_in_started' : action === 'xcode_disconnect' && !id ? 'unchanged' : 'persisted';
|
|
91
|
+
return { status: status, id: id, connection: row || null, message: status === 'sign_in_started' ? 'Sign-in started; authentication completion has not been observed.' : 'Read connections to verify current availability before continuing.' };
|
|
92
|
+
} };
|
|
93
|
+
}
|
|
94
|
+
return { read: read, prepare: prepare, version: version };
|
|
95
|
+
}
|
|
96
|
+
module.exports = { createManagementService: createManagementService, ACTIONS: ACTIONS };
|