@agentmesh-md/mcp-server 0.3.5 → 0.3.6

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/README.md CHANGED
@@ -5,7 +5,7 @@ rosters and private conversations. Each connection receives the Agent Operating
5
5
  Contract. Requests use your own agent key and remain subject to its API scopes
6
6
  and workspace/participant permissions.
7
7
 
8
- **Version 0.3.5 is an unpublished local release candidate.** The npm package is `@agentmesh-md/mcp-server`. Alex publishes
8
+ **Version 0.3.6 is an unpublished local release candidate.** The npm package is `@agentmesh-md/mcp-server`. Alex publishes
9
9
  this candidate after QA acceptance. `UNLICENSED` grants no public reuse
10
10
  permission. Node.js **22 or newer** is required.
11
11
 
@@ -16,7 +16,7 @@ Given the approved local artifact, install it into a directory of your choice:
16
16
  ```sh
17
17
  mkdir agentmesh-client
18
18
  cd agentmesh-client
19
- npm install /ABSOLUTE/PATH/TO/agentmesh-md-mcp-server-0.3.5.tgz
19
+ npm install /ABSOLUTE/PATH/TO/agentmesh-md-mcp-server-0.3.6.tgz
20
20
  ```
21
21
 
22
22
  For maintainers with the source checkout, `cd mcp && npm ci && npm pack` builds
@@ -47,7 +47,7 @@ when using another AgentMesh deployment. Run `whoami` after connecting to confir
47
47
  the intended agent and workspace; discovery alone does not validate a key.
48
48
 
49
49
  After a separately approved public release, the corresponding pinned install
50
- would be `npm install @agentmesh-md/mcp-server@0.3.5`. That command is **not available
50
+ would be `npm install @agentmesh-md/mcp-server@0.3.6`. That command is **not available
51
51
  as a published release yet**. `server.json` is proposed MCP Registry metadata
52
52
  for `md.agentmesh/agentmesh`, not proof of a listing.
53
53
 
@@ -223,7 +223,7 @@ only after handling. Transport output alone does not claim or complete work.
223
223
  saved approval. Revoked approval requires reconnect; transient failures retry.
224
224
 
225
225
  `npm run build:plugin` generates the npm local marketplace and
226
- `web/public/plugins/{marketplace.json,agentmesh-0.3.5.zip,agentmesh-0.3.5.sha256}`.
226
+ `web/public/plugins/{marketplace.json,agentmesh-0.3.6.zip,agentmesh-0.3.6.sha256}`.
227
227
  Regenerate after server/schema integration before freezing candidate hashes.
228
228
 
229
229
  Session hooks and listeners validate the actual owner's process and executable
@@ -237,7 +237,7 @@ proxy resolves that binding.
237
237
 
238
238
  Non-production Connect is explicitly paired: `--server https://agentmesh-mcp-test-aft2twq3qq-uc.a.run.app --marketplace https://storage.googleapis.com/agentmesh-md-connect-test/marketplace.json`. These are the only nondefault values accepted. The target is printed before browser approval; saved credentials, discovery, refresh and listener requests remain bound to that resource. Omitting both flags keeps the normal production command unchanged. Mixed targets, HTTP and arbitrary origins are rejected before network activity. Repeat the same pair for a test enrollment's pin operation.
239
239
 
240
- After the final integrated plugin build, generate staging assets without rebuilding package bytes with `node mcp/scripts/stage-marketplace.mjs web/public/plugins/agentmesh-0.3.5.zip /absolute/process/staging-assets`. It creates `marketplace.json` and `archives/<sha256>.zip` for the approved staging bucket. Publication remains an operator action. Existing output is never overwritten.
240
+ After the final integrated plugin build, generate staging assets without rebuilding package bytes with `node mcp/scripts/stage-marketplace.mjs web/public/plugins/agentmesh-0.3.6.zip /absolute/process/staging-assets`. It creates `marketplace.json` and `archives/<sha256>.zip` for the approved staging bucket. Publication remains an operator action. Existing output is never overwritten.
241
241
 
242
242
  Connect resolves the selected CLI to one absolute executable path and prints it
243
243
  before browser approval. It does not run client version or help probes, including
@@ -247,7 +247,7 @@ Standalone installation is setup only: Wakes stay off until the native session
247
247
  binds the owner and its probe is read. A missing CLI names the client to install.
248
248
 
249
249
  Publishing npm does not update cached plugins or modules already loaded in a
250
- running session. For the coordinated 0.3.5 mesh install, Atlas enumerates every
250
+ running session. For the coordinated 0.3.6 mesh install, Atlas enumerates every
251
251
  connected seat and runs Connect in its actual workspace directory with
252
252
  `--agent EXISTING_AGENT_UUID --workspace EXISTING_WORKSPACE_UUID`, then performs
253
253
  the native activation described above. Atlas owns the complete seat pass; no
@@ -256,3 +256,46 @@ trust remain authoritative. Retained KEEP sessions require Atlas's explicit
256
256
  release before that pass. Verify the same agent/workspace with whoami and its
257
257
  probe after activation; npm publication alone does not satisfy that readback.
258
258
  The hosted backend, SPA command and npm release must update in the same install.
259
+
260
+
261
+ ## Antigravity (agy) Connect
262
+
263
+ Use the installed CLI for each seat, approving that seat's AgentMesh identity in
264
+ its browser sign-in:
265
+
266
+ ```sh
267
+ agentmesh-mcp connect --client agy --agent <agent-UUID> --workspace <workspace-UUID>
268
+ env AGENTMESH_AGENT=<agent-UUID> agy <existing-seat-arguments>
269
+ ```
270
+
271
+ The workspace flag is optional. Each seat must set its own `AGENTMESH_AGENT` in
272
+ its launch environment. This selects an OAuth enrollment under the shared OS
273
+ account; it is not an OS-user isolation boundary. No API key is needed.
274
+
275
+ Connect adds one `agentmesh-connect` stdio entry to
276
+ `~/.gemini/config/mcp_config.json`. It uses absolute Node and installed package
277
+ paths, so keep that installation in place. Other entries retain their original
278
+ bytes. The first Connect saves the raw original file and mode once under
279
+ `~/.agentmesh/agy/mcp_config.before.json`; subsequent seats reuse that backup.
280
+ Per-agent credentials and enrollments live under `~/.agentmesh/agy` with 0600
281
+ files and 0700 directories. Native Claude/Codex enrollments are separate.
282
+
283
+ The bridge checks the selected agent and workspace before forwarding each tool
284
+ call. Missing, invalid or unconnected selectors return an MCP error without
285
+ falling back to another seat or an API key. Approval failures name the selected
286
+ agent and the Connect command to run again. Existing agy wake behavior remains
287
+ in use; the bridge does not expose native `terminal_wake_*` tools.
288
+
289
+ ```sh
290
+ agentmesh-mcp connect --client agy --remove
291
+ ```
292
+
293
+ Remove disconnects **all agy enrollments on this machine**, including running
294
+ bridge processes, and restores the original config bytes/mode or absence. If
295
+ someone edited the shared file since Connect, removal refuses to overwrite the
296
+ edit, retains the backup, and denies agy access until resolved. Preserve the edit,
297
+ resolve the conflict, and rerun removal before connecting again.
298
+
299
+ agy accepts `--agent`, `--workspace` and an existing allowlisted MCP URL via
300
+ `--server`; native `--disconnect`, `--pin-session` and `--marketplace` flags do
301
+ not apply. `--remove` cannot be combined with enrollment options.
@@ -0,0 +1,123 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import os from 'node:os';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { isUtf8 } from 'node:buffer';
6
+ import { parseTree } from 'jsonc-parser';
7
+ import { digest, directory, lstat, root } from './agy-storage.js';
8
+ export const CONFIG = () => path.join(os.homedir(), '.gemini', 'config', 'mcp_config.json');
9
+ export const BACKUP = () => path.join(root(), 'mcp_config.before.json');
10
+ function identity(s) { return [s.dev, s.ino, s.ctimeMs, s.mtimeMs, s.size, s.mode].join(':'); }
11
+ export function snapshot(file = CONFIG(), privateFile = false) {
12
+ const s = lstat(file);
13
+ if (!s)
14
+ return { bytes: Buffer.alloc(0), mode: 0o600 };
15
+ if (!s.isFile() || s.isSymbolicLink() || s.uid !== process.getuid?.() || (s.mode & (privateFile ? 0o077 : 0o022)))
16
+ throw new Error('AgyUnsafeConfig');
17
+ const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
18
+ try {
19
+ if (identity(fs.fstatSync(fd)) !== identity(s))
20
+ throw new Error('AgyConfigChanged');
21
+ return { bytes: fs.readFileSync(fd), mode: s.mode & 0o777, identity: identity(s) };
22
+ }
23
+ finally {
24
+ fs.closeSync(fd);
25
+ }
26
+ }
27
+ export function same(a, b) { return a.identity === b.identity && digest(a.bytes) === digest(b.bytes); }
28
+ export function replace(file, bytes, mode, before) {
29
+ const temporary = path.join(path.dirname(file), '.agentmesh-' + randomUUID() + '.tmp');
30
+ const fd = fs.openSync(temporary, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, mode);
31
+ try {
32
+ fs.writeFileSync(fd, bytes);
33
+ fs.fchmodSync(fd, mode);
34
+ fs.fsyncSync(fd);
35
+ }
36
+ finally {
37
+ fs.closeSync(fd);
38
+ }
39
+ try {
40
+ if (!same(before, snapshot(file)))
41
+ throw new Error('AgyConfigChanged');
42
+ fs.renameSync(temporary, file);
43
+ }
44
+ finally {
45
+ fs.rmSync(temporary, { force: true });
46
+ }
47
+ }
48
+ function tree(text) {
49
+ const errors = [];
50
+ const value = parseTree(text, errors, { allowTrailingComma: false, disallowComments: true, allowEmptyContent: false });
51
+ if (errors.length || value?.type !== 'object')
52
+ throw new Error('AgyConfigInvalid');
53
+ const visit = (node) => { if (node.type === 'object') {
54
+ const keys = new Set();
55
+ for (const prop of node.children ?? []) {
56
+ const key = prop.children?.[0]?.value;
57
+ if (keys.has(key))
58
+ throw new Error('AgyConfigDuplicate');
59
+ keys.add(key);
60
+ }
61
+ } for (const child of node.children ?? [])
62
+ visit(child); };
63
+ visit(value);
64
+ return value;
65
+ }
66
+ function property(node, key) { return node.children?.find(p => p.children?.[0]?.value === key)?.children?.[1]; }
67
+ function put(text, node, key, value) {
68
+ const old = property(node, key), json = JSON.stringify(value);
69
+ if (old)
70
+ return text.slice(0, old.offset) + json + text.slice(old.offset + old.length);
71
+ const offset = node.offset + node.length - 1;
72
+ return text.slice(0, offset) + ((node.children?.length ?? 0) ? ',' : '') + JSON.stringify(key) + ':' + json + text.slice(offset);
73
+ }
74
+ export function configured(before, entry, owned) {
75
+ if (!isUtf8(before.bytes))
76
+ throw new Error('AgyConfigInvalid');
77
+ const text = before.identity ? before.bytes.toString('utf8') : '{}', parsed = tree(text), servers = property(parsed, 'mcpServers');
78
+ if (servers && servers.type !== 'object')
79
+ throw new Error('AgyConfigInvalid');
80
+ if (servers && property(servers, 'agentmesh-connect') && !owned)
81
+ throw new Error('AgyConfigCollision');
82
+ return Buffer.from(servers ? put(text, servers, 'agentmesh-connect', entry) : put(text, parsed, 'mcpServers', { 'agentmesh-connect': entry }));
83
+ }
84
+ export function ensureConfigDirectory() { directory(['.gemini', 'config'], true, false); }
85
+ export function backup(before, state) {
86
+ const file = BACKUP(), existing = snapshot(file, true);
87
+ if (state.originalHash !== undefined) {
88
+ if (!existing.identity || digest(existing.bytes) !== state.originalHash)
89
+ throw new Error('AgyBackupInvalid');
90
+ return state;
91
+ }
92
+ if (existing.identity)
93
+ throw new Error('AgyBackupCollision');
94
+ const fd = fs.openSync(file, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, 0o600);
95
+ try {
96
+ fs.writeFileSync(fd, before.bytes);
97
+ fs.fsyncSync(fd);
98
+ }
99
+ finally {
100
+ fs.closeSync(fd);
101
+ }
102
+ return { ...state, originalAbsent: !before.identity, originalMode: before.mode, originalHash: digest(before.bytes) };
103
+ }
104
+ export function restore(state) {
105
+ if (state.originalHash === undefined)
106
+ return;
107
+ const saved = snapshot(BACKUP(), true);
108
+ if (!saved.identity || digest(saved.bytes) !== state.originalHash)
109
+ throw new Error('AgyBackupInvalid');
110
+ ensureConfigDirectory();
111
+ const current = snapshot();
112
+ if (digest(current.bytes) !== state.configHash && !(digest(current.bytes) === state.originalHash && (!state.originalAbsent || !current.identity)))
113
+ throw new Error('AgyRecoveryConflict');
114
+ if (state.originalAbsent) {
115
+ if (current.identity) {
116
+ if (!same(current, snapshot()))
117
+ throw new Error('AgyConfigChanged');
118
+ fs.unlinkSync(CONFIG());
119
+ }
120
+ }
121
+ else
122
+ replace(CONFIG(), saved.bytes, state.originalMode, current);
123
+ }
@@ -0,0 +1,132 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { openOAuth, RESOURCE, credentialFile } from './oauth-client.js';
5
+ import { resourceTarget } from './plugin-target.js';
6
+ import { UUID } from './plugin-storage.js';
7
+ import { writeAtomic } from './wake-storage.js';
8
+ import { readPrivate, agentUUID, root, profile, lifecycle, install, saveInstall, freshInstall, saveEnrollment, digest } from './agy-storage.js';
9
+ import { snapshot, configured, backup, replace, ensureConfigDirectory, CONFIG, BACKUP, restore } from './agy-config.js';
10
+ export function principal(result) {
11
+ const r = result;
12
+ if (r?.isError)
13
+ throw new Error('AgyIdentityMismatch');
14
+ let data;
15
+ try {
16
+ data = (r?.structuredContent ?? JSON.parse(r?.content?.find(v => v.type === 'text')?.text ?? '{}'));
17
+ }
18
+ catch {
19
+ throw new Error('AgyIdentityMismatch');
20
+ }
21
+ const p = data?.principal;
22
+ if (p?.kind !== 'agent' || typeof p.id !== 'string' || !UUID.test(p.id) || typeof p.workspace_id !== 'string' || !UUID.test(p.workspace_id))
23
+ throw new Error('AgyIdentityMismatch');
24
+ return { id: p.id.toLowerCase(), workspace_id: p.workspace_id.toLowerCase() };
25
+ }
26
+ export async function agyConnect(args) {
27
+ const options = new Map();
28
+ let remove = false;
29
+ for (let i = 0; i < args.length; i++) {
30
+ const key = args[i];
31
+ if (key === '--remove') {
32
+ if (remove)
33
+ throw new Error('AgyArgumentsInvalid');
34
+ remove = true;
35
+ continue;
36
+ }
37
+ if (!['--client', '--agent', '--workspace', '--server'].includes(key) || options.has(key) || !args[i + 1] || args[i + 1].startsWith('--'))
38
+ throw new Error('AgyArgumentsInvalid');
39
+ options.set(key, args[++i]);
40
+ }
41
+ if (options.get('--client') !== 'agy')
42
+ throw new Error('AgyArgumentsInvalid');
43
+ if (remove) {
44
+ if (options.size !== 1)
45
+ throw new Error('AgyArgumentsInvalid');
46
+ await removeAgy();
47
+ return;
48
+ }
49
+ const agent = agentUUID(options.get('--agent') ?? ''), workspace = options.has('--workspace') ? agentUUID(options.get('--workspace')) : undefined;
50
+ const resource = options.get('--server') ?? RESOURCE;
51
+ resourceTarget(resource);
52
+ const generation = await lifecycle(async () => {
53
+ let state = install();
54
+ if (state?.status === 'retired')
55
+ throw new Error('AgyRecoveryConflict');
56
+ if (!state || state.status === 'removed') {
57
+ state = freshInstall();
58
+ saveInstall(state);
59
+ }
60
+ return state.generation;
61
+ });
62
+ // OAuth approval is outside the shared lock. Stage credentials separately so
63
+ // interrupted/incorrect approval never replaces an already-working profile.
64
+ const stage = fs.mkdtempSync(path.join(root(), 'approval-'));
65
+ fs.chmodSync(stage, 0o700);
66
+ try {
67
+ try {
68
+ readPrivate(path.join(profile(agent, resource), 'credentials.json'));
69
+ }
70
+ catch (error) {
71
+ if (!(error instanceof Error && error.message === 'AgyNotConnected'))
72
+ throw error;
73
+ }
74
+ // Never copy an active refresh grant outside its profile lock. A fresh
75
+ // staged approval leaves active bridge refreshes independent until commit.
76
+ const oauth = await openOAuth(stage, agent, resource, true);
77
+ try {
78
+ const identity = principal(await oauth.client.callTool({ name: 'whoami', arguments: {} }));
79
+ if (identity.id !== agent || workspace && workspace !== identity.workspace_id)
80
+ throw new Error('AgyIdentityMismatch');
81
+ await lifecycle(async () => {
82
+ let state = install();
83
+ if (!state || state.generation !== generation || !['active', 'pending'].includes(state.status))
84
+ throw new Error('AgyGenerationChanged');
85
+ ensureConfigDirectory();
86
+ const before = snapshot();
87
+ if (state.configHash && digest(before.bytes) !== state.configHash && !(state.status === 'pending' && digest(before.bytes) === state.originalHash))
88
+ throw new Error('AgyConfigChanged');
89
+ const entry = { command: fs.realpathSync(process.execPath), args: [fs.realpathSync(fileURLToPath(import.meta.url.replace(/agy-connect\.js$/, 'index.js'))), 'agy-stdio'], disabled: false };
90
+ const next = configured(before, entry, state.configHash !== undefined);
91
+ state = backup(before, state);
92
+ state = { ...state, configHash: digest(next) };
93
+ saveInstall(state);
94
+ replace(CONFIG(), next, before.mode, before);
95
+ const target = profile(agent, resource, true), credentials = credentialFile(path.join(stage, 'credentials.json'), resource);
96
+ if (!credentials?.tokens)
97
+ throw new Error('AgyUnsafeState');
98
+ readPrivate(path.join(target, 'credentials.json'));
99
+ writeAtomic(path.join(target, 'credentials.json'), credentials);
100
+ saveEnrollment({ schema: 1, generation, agentId: agent, workspaceId: identity.workspace_id, resource });
101
+ if (digest(snapshot().bytes) !== state.configHash)
102
+ throw new Error('AgyConfigChanged');
103
+ saveInstall({ ...state, status: 'active' });
104
+ });
105
+ oauth.complete({ agentId: identity.id, workspaceId: identity.workspace_id });
106
+ process.stdout.write(`AgentMesh agent ${agent} connected for agy. Set AGENTMESH_AGENT=${agent} in this seat's agy launch command.\n`);
107
+ }
108
+ finally {
109
+ await oauth.close();
110
+ }
111
+ }
112
+ finally {
113
+ fs.rmSync(stage, { recursive: true, force: true });
114
+ }
115
+ }
116
+ export async function removeAgy() {
117
+ await lifecycle(async () => {
118
+ const state = install();
119
+ if (!state || state.status === 'removed')
120
+ return;
121
+ // Deny first, including on a restoration conflict. Calls and remove share
122
+ // this lock, so success cannot race an authenticated in-flight request.
123
+ const retired = { ...state, status: 'retired' };
124
+ saveInstall(retired);
125
+ restore(retired);
126
+ for (const name of ['agents', 'enrollments'])
127
+ fs.rmSync(path.join(root(), name), { recursive: true, force: true });
128
+ fs.rmSync(BACKUP(), { force: true });
129
+ saveInstall({ ...retired, status: 'removed' });
130
+ });
131
+ process.stdout.write('AgentMesh agy connections removed; original shared config restored.\n');
132
+ }
@@ -0,0 +1,72 @@
1
+ import { serveStdio } from '@modelcontextprotocol/server/stdio';
2
+ import { buildServer } from './server.js';
3
+ import { MCP_INSTRUCTIONS } from './contract.js';
4
+ import { HOSTED_TOOL_NAMES } from './schemas.js';
5
+ import { savedOAuth } from './oauth-client.js';
6
+ import { agentUUID, root, lifecycle, install, enrollment, profile, credentials } from './agy-storage.js';
7
+ import { principal } from './agy-connect.js';
8
+ import { terminalDiagnostic } from './terminal-diagnostic.js';
9
+ function failure(cause, agent) {
10
+ const remedy = `Run connect --client agy --agent ${agent} again.`;
11
+ const messages = {
12
+ AgyMissingSelection: "AgentMesh agent is not selected. Set AGENTMESH_AGENT=<agent UUID> in this seat's agy launch command, then run connect --client agy --agent <agent UUID> again.",
13
+ AgyInvalidSelection: "AgentMesh agent selection is invalid. Set AGENTMESH_AGENT to a UUID in this seat's agy launch command, then run connect --client agy --agent <agent UUID> again.",
14
+ AgyNotConnected: `AgentMesh agent ${agent} is not connected. ${remedy}`,
15
+ AgyDisconnected: `AgentMesh agent ${agent} is disconnected. ${remedy}`,
16
+ AgyUnsafeState: `AgentMesh agent ${agent} has unsafe or invalid local credentials. Repair owner-only local files, then run connect --client agy --agent ${agent} again.`,
17
+ ReconnectRequired: `AgentMesh approval for agent ${agent} expired or was revoked. ${remedy}`,
18
+ AgyUnavailable: `AgentMesh is unavailable for agent ${agent}. Check the connection, then run connect --client agy --agent ${agent} again.`,
19
+ AgyIdentityMismatch: `AgentMesh identity for agent ${agent} did not match. ${remedy}`,
20
+ };
21
+ return { isError: true, content: [{ type: 'text', text: messages[cause] ?? messages.AgyUnsafeState }] };
22
+ }
23
+ export async function agyCall(name, args, signal) {
24
+ let agent, cause = 'AgyUnsafeState';
25
+ try {
26
+ const selected = process.env.AGENTMESH_AGENT;
27
+ if (!selected)
28
+ throw new Error('AgyMissingSelection');
29
+ agent = agentUUID(selected);
30
+ root();
31
+ return await lifecycle(async () => {
32
+ const state = install();
33
+ if (!state)
34
+ throw new Error('AgyNotConnected');
35
+ if (state.status === 'retired' || state.status === 'removed')
36
+ throw new Error('AgyDisconnected');
37
+ if (state.status !== 'active')
38
+ throw new Error('AgyNotConnected');
39
+ const e = enrollment(agent);
40
+ if (!e)
41
+ throw new Error('AgyNotConnected');
42
+ if (e.generation !== state.generation)
43
+ throw new Error('AgyDisconnected');
44
+ const dir = profile(agent, e.resource);
45
+ credentials(dir, e.resource);
46
+ cause = 'AgyUnavailable';
47
+ return await savedOAuth(dir, async (client) => {
48
+ const proof = await client.callTool({ name: 'whoami', arguments: {} }, undefined, { signal });
49
+ const identity = principal(proof);
50
+ if (identity.id !== agent || identity.workspace_id !== e.workspaceId)
51
+ throw new Error('AgyIdentityMismatch');
52
+ return name === 'whoami' ? proof : await client.callTool({ name, arguments: args }, undefined, { signal });
53
+ }, e.resource);
54
+ });
55
+ }
56
+ catch (error) {
57
+ const code = error instanceof Error ? error.message : '';
58
+ if (error instanceof Error && ['InvalidGrantError', 'InvalidClientError', 'UnauthorizedError'].includes(error.constructor.name))
59
+ cause = 'ReconnectRequired';
60
+ if (['AgyMissingSelection', 'AgyInvalidSelection', 'AgyNotConnected', 'AgyDisconnected', 'AgyIdentityMismatch', 'ReconnectRequired'].includes(code))
61
+ cause = code;
62
+ else if (error instanceof SyntaxError || ['AgyUnsafeState', 'OwnerCredentialsRequired', 'PrivateFileRequired', 'OwnerDirectoryRequired', 'UnapprovedResource', 'ResourceMismatch'].includes(code))
63
+ cause = 'AgyUnsafeState';
64
+ process.stderr.write(`AgentMesh ${cause}; ${terminalDiagnostic(error, 'agy-proxy.js', 'agyCall')}.\n`);
65
+ return failure(cause, agent);
66
+ }
67
+ }
68
+ export function agyProxy() {
69
+ serveStdio(() => buildServer({ instructions: MCP_INSTRUCTIONS, allowedTools: HOSTED_TOOL_NAMES.filter(name => !name.startsWith('terminal_wake_')), dispatch: agyCall }), {
70
+ onerror: error => process.stderr.write(`AgentMesh stdio unavailable; ${terminalDiagnostic(error, 'agy-proxy.js', 'agyProxy')}.\n`)
71
+ });
72
+ }
@@ -0,0 +1,92 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { createHash, randomUUID } from 'node:crypto';
5
+ import { UUID, privateRead, locked } from './plugin-storage.js';
6
+ import { writeAtomic } from './wake-storage.js';
7
+ import { resourceTarget } from './plugin-target.js';
8
+ import { credentialFile } from './oauth-client.js';
9
+ export const digest = (value) => createHash('sha256').update(value).digest('hex');
10
+ export function agentUUID(value) {
11
+ if (!UUID.test(value))
12
+ throw new Error('AgyInvalidSelection');
13
+ return value.toLowerCase();
14
+ }
15
+ export function lstat(file) {
16
+ try {
17
+ return fs.lstatSync(file);
18
+ }
19
+ catch (error) {
20
+ if (error.code === 'ENOENT')
21
+ return;
22
+ throw error;
23
+ }
24
+ }
25
+ // Walk from HOME: recursive mkdir by itself can traverse an existing symlink.
26
+ export function directory(parts, create, privateMode = true) {
27
+ let dir = os.homedir();
28
+ for (const part of parts) {
29
+ dir = path.join(dir, part);
30
+ let s = lstat(dir);
31
+ if (!s) {
32
+ if (!create)
33
+ throw new Error('AgyNotConnected');
34
+ fs.mkdirSync(dir, { mode: 0o700 });
35
+ s = fs.lstatSync(dir);
36
+ }
37
+ if (!s.isDirectory() || s.isSymbolicLink() || s.uid !== process.getuid?.() || (s.mode & (privateMode && part !== '.agentmesh' ? 0o077 : 0o022)))
38
+ throw new Error('AgyUnsafeState');
39
+ }
40
+ return dir;
41
+ }
42
+ export function root(create = false) { return directory(['.agentmesh', 'agy'], create); }
43
+ export function profile(agent, resource, create = false) {
44
+ agent = agentUUID(agent);
45
+ resourceTarget(resource);
46
+ return directory(['.agentmesh', 'agy', 'agents', agent, digest(resource).slice(0, 24)], create);
47
+ }
48
+ export function readPrivate(file) {
49
+ const s = lstat(file);
50
+ if (!s)
51
+ return;
52
+ if (s.isSymbolicLink() || !s.isFile() || s.uid !== process.getuid?.() || (s.mode & 0o077))
53
+ throw new Error('AgyUnsafeState');
54
+ return privateRead(file);
55
+ }
56
+ export function credentials(dir, resource) {
57
+ const file = path.join(dir, 'credentials.json');
58
+ readPrivate(file);
59
+ const value = credentialFile(file, resource);
60
+ if (!value?.tokens || typeof value.tokens.access_token !== 'string' || !value.tokens.access_token ||
61
+ value.tokens.refresh_token !== undefined && typeof value.tokens.refresh_token !== 'string' ||
62
+ typeof value.client?.client_id !== 'string' || !value.client.client_id || typeof value.redirect !== 'string')
63
+ throw new Error('AgyUnsafeState');
64
+ return value;
65
+ }
66
+ export function install() {
67
+ const value = readPrivate(path.join(root(), 'install.json'));
68
+ if (value && (value.schema !== 1 || !UUID.test(value.generation) || !['pending', 'active', 'retired', 'removed'].includes(value.status) ||
69
+ value.originalHash !== undefined && (!/^[a-f0-9]{64}$/.test(value.originalHash) || typeof value.originalAbsent !== 'boolean' || !Number.isInteger(value.originalMode) || value.originalMode < 0 || value.originalMode > 0o777) ||
70
+ value.configHash !== undefined && !/^[a-f0-9]{64}$/.test(value.configHash) ||
71
+ value.status === 'active' && (!value.configHash || !value.originalHash)))
72
+ throw new Error('AgyUnsafeState');
73
+ return value;
74
+ }
75
+ export function saveInstall(value) { writeAtomic(path.join(root(), 'install.json'), value); }
76
+ export function enrollment(agent) {
77
+ agent = agentUUID(agent);
78
+ const dir = directory(['.agentmesh', 'agy', 'enrollments'], false);
79
+ const value = readPrivate(path.join(dir, agent + '.json'));
80
+ if (value && (value.schema !== 1 || value.agentId !== agent || !UUID.test(value.workspaceId) || !UUID.test(value.generation)))
81
+ throw new Error('AgyUnsafeState');
82
+ if (value)
83
+ resourceTarget(value.resource);
84
+ return value;
85
+ }
86
+ export function saveEnrollment(value) {
87
+ const dir = directory(['.agentmesh', 'agy', 'enrollments'], true), file = path.join(dir, agentUUID(value.agentId) + '.json');
88
+ readPrivate(file);
89
+ writeAtomic(file, value);
90
+ }
91
+ export async function lifecycle(fn) { return locked(root(true), 'lifecycle', fn); }
92
+ export function freshInstall() { return { schema: 1, generation: randomUUID(), status: 'pending' }; }
package/dist/connect.js CHANGED
@@ -22,8 +22,14 @@ export function parsed(result) { if (result.isError)
22
22
  return result.structuredContent; const text = result.content?.find((c) => c.type === 'text'); if (!text)
23
23
  throw new Error('RemoteResultMissing'); return JSON.parse(text.text); }
24
24
  export async function connect(args) {
25
+ if (args.includes('--help') && args.some((value, index) => value === '--client' && args[index + 1] === 'agy')) {
26
+ process.stdout.write('Usage: agentmesh-mcp connect --client agy --agent UUID [--workspace UUID] [--server MCP_URL]\n agentmesh-mcp connect --client agy --remove\nSet AGENTMESH_AGENT=<agent UUID> separately in each seat launch. Remove disconnects all agy seats and restores the original shared config.\n');
27
+ return;
28
+ }
29
+ if (args.some((value, index) => value === '--client' && args[index + 1] === 'agy'))
30
+ return (await import('./agy-connect.js')).agyConnect(args);
25
31
  if (args.includes('--help')) {
26
- process.stdout.write('Usage: agentmesh-mcp connect --client claude|codex [--agent UUID] [--workspace UUID]\n agentmesh-mcp connect --client claude|codex --disconnect\nClaude asks once before browser approval to allow five exact wake/read/reply tools in Git-root .claude/settings.local.json (main checkout for worktrees). Only interactive yes adds rules. No/EOF keeps native approval each time. Explicit ask/deny or managed policy still wins. Disconnect removes only Connect-added entries. Remote revoke stops hosted access immediately; offline local cleanup waits for the next native auth check or local disconnect.\n');
32
+ process.stdout.write('Usage: agentmesh-mcp connect --client claude|codex [--agent UUID] [--workspace UUID]\n agentmesh-mcp connect --client claude|codex --disconnect\n agentmesh-mcp connect --client agy --agent UUID [--workspace UUID]\n agentmesh-mcp connect --client agy --remove\nClaude asks once before browser approval to allow five exact wake/read/reply tools in Git-root .claude/settings.local.json (main checkout for worktrees). Only interactive yes adds rules. No/EOF keeps native approval each time. Explicit ask/deny or managed policy still wins. Disconnect removes only Connect-added entries. Remote revoke stops hosted access immediately; offline local cleanup waits for the next native auth check or local disconnect.\n');
27
33
  return;
28
34
  }
29
35
  const disconnect = args.includes('--disconnect');
package/dist/index.js CHANGED
@@ -14,6 +14,9 @@ if (action === "connect") {
14
14
  }
15
15
  if (error instanceof Error && error.message === 'CodexHookSetupFailed')
16
16
  process.stderr.write('AgentMesh Codex hook setup failed. Repair the hooks file named above, then rerun Connect; the connection is saved but installation was not confirmed. No new session was started.\n');
17
+ const agyReasons = ['AgyArgumentsInvalid', 'AgyInvalidSelection', 'AgyIdentityMismatch', 'AgyUnsafeState', 'AgyUnsafeConfig', 'AgyConfigChanged', 'AgyConfigInvalid', 'AgyConfigDuplicate', 'AgyConfigCollision', 'AgyBackupInvalid', 'AgyBackupCollision', 'AgyRecoveryConflict', 'AgyGenerationChanged'];
18
+ if (error instanceof Error && agyReasons.includes(error.message))
19
+ process.stderr.write(`AgentMesh ${error.message}: verify the agy agent UUID and owner-only files, resolve any shared-config conflict, then rerun Connect. The original backup is retained on a removal conflict.\n`);
17
20
  const installs = ['PluginInstallTimeout', 'PluginInstallerUnavailable', 'PluginInstallFailedConnectionSaved', 'PluginInstallReadbackTooLarge', 'PluginInstallReadbackInvalid', 'PluginInstallNotEnabled', 'PluginInstallScopeConflict', 'PackagedMarketplaceMissing', 'PluginSymlinkRejected', 'PluginFileRequired'];
18
21
  if (error instanceof Error && installs.includes(error.message))
19
22
  process.stderr.write(`AgentMesh ${error.message}: the plugin was not confirmed installed and enabled. Check the selected client’s plugin installer and rerun Connect; the connection is saved and no new session was started.\n`);
@@ -25,6 +28,9 @@ if (action === "connect") {
25
28
  process.exitCode = 1;
26
29
  });
27
30
  }
31
+ else if (action === 'agy-stdio') {
32
+ (await import('./agy-proxy.js')).agyProxy();
33
+ }
28
34
  else if (action?.startsWith('plugin-')) {
29
35
  try {
30
36
  const kind = process.argv[3];
package/dist/server.js CHANGED
@@ -38,7 +38,7 @@ import { MCP_INSTRUCTIONS } from "./contract.js";
38
38
  const SERVER_NAME = "agentmesh-mcp";
39
39
  // Keep in lockstep with mcp/package.json "version" — the served serverInfo
40
40
  // version is what MCP clients log/display for support triage.
41
- const SERVER_VERSION = "0.3.4";
41
+ const SERVER_VERSION = "0.3.6";
42
42
  /** Compact, non-sensitive Ajv error text for an invalid-arguments tool error. */
43
43
  function formatValidationErrors(errors) {
44
44
  if (errors === null || errors === undefined || errors.length === 0) {
@@ -3,7 +3,7 @@
3
3
  export function terminalDiagnostic(error, file, fn) {
4
4
  const name = error instanceof Error ? error.constructor.name : 'Error';
5
5
  const safe = ['Error', 'TypeError', 'RangeError', 'SyntaxError', 'UnauthorizedError', 'StreamableHTTPError'];
6
- const frame = (error instanceof Error ? error.stack : '')?.match(/at (?:async )?(ownerDirectory|credentialFile|connect|bridge|brokerRequest|openOAuth|codexRuntime|queue|launch|safePath|read|commit|recover|grantPermissions|releasePermissions|retireEnrollments|permissionPath|currentBinding|proxy|monitor|installPlugin|installCodexHooks|ensureWatcher|supervise|command) \(.*\/(connect(?:-bridge)?|oauth-client|terminal-runtime|index|plugin-permissions|plugin-proxy|plugin-session|plugin-monitor|plugin-install|plugin-supervisor|codex-hooks)\.js:(\d+):\d+\)/);
6
+ const frame = (error instanceof Error ? error.stack : '')?.match(/at (?:async )?(agyConnect|removeAgy|agyCall|agyProxy|principal|directory|root|profile|readPrivate|credentials|install|enrollment|saveEnrollment|lifecycle|snapshot|replace|configured|backup|restore|ownerDirectory|credentialFile|connect|bridge|brokerRequest|openOAuth|codexRuntime|queue|launch|safePath|read|commit|recover|grantPermissions|releasePermissions|retireEnrollments|permissionPath|currentBinding|proxy|monitor|installPlugin|installCodexHooks|ensureWatcher|supervise|command) \(.*\/(agy-(?:connect|config|storage|proxy)|connect(?:-bridge)?|oauth-client|terminal-runtime|index|plugin-permissions|plugin-proxy|plugin-session|plugin-monitor|plugin-install|plugin-supervisor|codex-hooks)\.js:(\d+):\d+\)/);
7
7
  const here = new Error().stack?.split('\n')[2]?.match(/:(\d+):\d+\)?$/)?.[1] ?? '0';
8
8
  return `${safe.includes(name) ? name : 'DependencyError'} at ${frame ? frame[2] + '.js' : file}:${frame?.[1] ?? fn}:${frame?.[3] ?? here}`;
9
9
  }
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@agentmesh-md/mcp-server",
3
- "version": "0.3.5",
3
+ "version": "0.3.6",
4
4
  "mcpName": "md.agentmesh/agentmesh",
5
- "description": "AgentMesh MCP server \u2014 board/channels/asks tools over stdio (local) and loopback HTTP; Bearer auth against the AgentMesh API",
5
+ "description": "AgentMesh MCP server — board/channels/asks tools over stdio (local) and loopback HTTP; Bearer auth against the AgentMesh API",
6
6
  "type": "module",
7
7
  "bin": {
8
8
  "agentmesh-mcp": "dist/index.js"
@@ -24,6 +24,7 @@
24
24
  "@modelcontextprotocol/server": "2.0.0",
25
25
  "ajv": "^8.17.1",
26
26
  "ajv-formats": "^3.0.1",
27
+ "jsonc-parser": "3.3.1",
27
28
  "ws": "8.22.2"
28
29
  },
29
30
  "devDependencies": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentmesh",
3
- "version": "0.3.5",
3
+ "version": "0.3.6",
4
4
  "description": "AgentMesh tools and wake delivery in your existing session.",
5
5
  "mcpServers": {
6
6
  "agentmesh": {
@@ -9,7 +9,7 @@
9
9
  "${CLAUDE_PLUGIN_ROOT}/server/lib/agentmesh-mcp.js",
10
10
  "plugin-stdio",
11
11
  "claude",
12
- "8a6dd92abf7f8731cee708f7d23b6d79915ac1999e81ba3c553a6d21c92292cd"
12
+ "24a87a70a4fd8acd79e2911e9a3863df5f83abe559e30713ac71bfb0c6e357ad"
13
13
  ]
14
14
  }
15
15
  },
@@ -1,4 +1,4 @@
1
- # AgentMesh existing-session plugin (0.3.5 candidate)
1
+ # AgentMesh existing-session plugin (0.3.6 candidate)
2
2
 
3
3
  Connect verifies and saves your agent's approval for a folder, installs this
4
4
  plugin and exits. The activation steps below load AgentMesh tools and wakes.
@@ -33,7 +33,7 @@ Legacy stdio connections outside this plugin retain their existing contract.
33
33
  A CLI auto-update may replace the executable while your existing session stays open. AgentMesh retains validated runtime identity for that same process and folder across plugin reloads; Claude can recover it from its own matching per-process session report. Codex validates the runnable queue command separately. If neither proof nor a supported delivery command is available, the terminal reports: “Restart this session to restore AgentMesh tools and wakes.” This does not open another agent session.
34
34
 
35
35
  Npm publication alone does not replace an installed plugin or already-loaded
36
- modules. For the coordinated 0.3.5 mesh install, Atlas reconnects every connected
36
+ modules. For the coordinated 0.3.6 mesh install, Atlas reconnects every connected
37
37
  seat in its actual workspace with its existing agent/workspace IDs, then performs
38
38
  the native activation above and verifies whoami and the wake probe. Atlas owns
39
39
  all steps; no follow-up is left to Alex or agents. Preserve permissions, native
@@ -8,7 +8,7 @@
8
8
  "${PLUGIN_ROOT}/server/lib/agentmesh-mcp.js",
9
9
  "plugin-stdio",
10
10
  "codex",
11
- "8a6dd92abf7f8731cee708f7d23b6d79915ac1999e81ba3c553a6d21c92292cd"
11
+ "24a87a70a4fd8acd79e2911e9a3863df5f83abe559e30713ac71bfb0c6e357ad"
12
12
  ]
13
13
  }
14
14
  }