@agentmesh-md/mcp-server 0.3.6 → 0.3.8

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/dist/index.js CHANGED
@@ -5,7 +5,14 @@ if (action === "connect") {
5
5
  const { connect } = await import("./connect.js");
6
6
  const { terminalDiagnostic } = await import("./terminal-diagnostic.js");
7
7
  const { ClientExecutableMissing } = await import("./terminal-runtime.js");
8
- await connect(process.argv.slice(3)).catch((error) => {
8
+ await connect(process.argv.slice(3)).catch(async (error) => {
9
+ if (process.argv.some((value, index) => value === '--client' && process.argv[index + 1] === 'agy')) {
10
+ const { agyMessages, agyReason } = await import('./agy-storage.js');
11
+ process.stderr.write(agyMessages[agyReason(error, 'AgyApprovalFailed')] + '\n');
12
+ process.stderr.write(`AgentMesh ${terminalDiagnostic(error, 'index.js', 'connect')}.\n`);
13
+ process.exitCode = 1;
14
+ return;
15
+ }
9
16
  if (error instanceof ClientExecutableMissing) {
10
17
  const name = error.client === 'claude' ? 'Claude Code' : 'Codex';
11
18
  process.stderr.write(`AgentMesh could not find ${name} (${error.client}) on PATH. Install ${name}, then run Connect again.\n`);
@@ -14,9 +21,6 @@ if (action === "connect") {
14
21
  }
15
22
  if (error instanceof Error && error.message === 'CodexHookSetupFailed')
16
23
  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`);
20
24
  const installs = ['PluginInstallTimeout', 'PluginInstallerUnavailable', 'PluginInstallFailedConnectionSaved', 'PluginInstallReadbackTooLarge', 'PluginInstallReadbackInvalid', 'PluginInstallNotEnabled', 'PluginInstallScopeConflict', 'PackagedMarketplaceMissing', 'PluginSymlinkRejected', 'PluginFileRequired'];
21
25
  if (error instanceof Error && installs.includes(error.message))
22
26
  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`);
@@ -31,6 +35,19 @@ if (action === "connect") {
31
35
  else if (action === 'agy-stdio') {
32
36
  (await import('./agy-proxy.js')).agyProxy();
33
37
  }
38
+ else if (action === 'agy-hook' || action === 'agy-monitor') {
39
+ try {
40
+ if (action === 'agy-hook')
41
+ await (await import('./agy-hooks.js')).agyHook();
42
+ else
43
+ await (await import('./agy-monitor.js')).agyMonitor();
44
+ }
45
+ catch (error) {
46
+ const { terminalDiagnostic } = await import('./terminal-diagnostic.js');
47
+ process.stderr.write(`AgentMesh wakes are Off. Restart agy in the connected folder, send your first message and approve the startup command. ${terminalDiagnostic(error, 'index.js', action)}.\n`);
48
+ process.exitCode = 1;
49
+ }
50
+ }
34
51
  else if (action?.startsWith('plugin-')) {
35
52
  try {
36
53
  const kind = process.argv[3];
@@ -35,6 +35,7 @@ class Provider {
35
35
  requestedAgentId;
36
36
  interactive;
37
37
  resource;
38
+ onTokens;
38
39
  verifier = '';
39
40
  secrets = new Set();
40
41
  redact(value) {
@@ -52,11 +53,12 @@ class Provider {
52
53
  saved;
53
54
  redirectUrl;
54
55
  authorizationStarted = false;
55
- constructor(file, redirect, requestedAgentId, interactive = true, resource = RESOURCE) {
56
+ constructor(file, redirect, requestedAgentId, interactive = true, resource = RESOURCE, onTokens) {
56
57
  this.file = file;
57
58
  this.requestedAgentId = requestedAgentId;
58
59
  this.interactive = interactive;
59
60
  this.resource = resource;
61
+ this.onTokens = onTokens;
60
62
  this.saved = credentialFile(file, resource) ?? { resource, redirect };
61
63
  this.redirectUrl = redirect;
62
64
  this.saved.redirect = redirect;
@@ -72,7 +74,7 @@ class Provider {
72
74
  clientInformation() { return this.saved.client; }
73
75
  saveClientInformation(value) { this.saved.client = value; this.save(); }
74
76
  tokens() { return this.saved.tokens; }
75
- saveTokens(value) { this.remember(value); this.saved.tokens = value; this.save(); }
77
+ async saveTokens(value) { this.remember(value); this.saved.tokens = value; this.save(); await this.onTokens?.(); }
76
78
  saveCodeVerifier(value) { this.verifier = value; }
77
79
  codeVerifier() { return this.verifier; }
78
80
  async validateResourceURL(server, resource) {
@@ -114,7 +116,7 @@ const safeFetch = (resource, timeout = 15_000) => async (input, init) => {
114
116
  throw new Error('OAuthOriginMismatch');
115
117
  return fetch(input, { ...init, redirect: 'error', signal: init?.signal ? AbortSignal.any([init.signal, AbortSignal.timeout(timeout)]) : AbortSignal.timeout(timeout) });
116
118
  };
117
- export async function openOAuth(profile, requestedAgentId, resource = RESOURCE, freshApproval = false) {
119
+ export async function openOAuth(profile, requestedAgentId, resource = RESOURCE, freshApproval = false, options = {}) {
118
120
  const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
119
121
  if (requestedAgentId !== undefined && !uuid.test(requestedAgentId))
120
122
  throw new Error('IdentityArgument');
@@ -147,12 +149,14 @@ export async function openOAuth(profile, requestedAgentId, resource = RESOURCE,
147
149
  const address = server.address();
148
150
  if (!address || typeof address === 'string')
149
151
  throw new Error('CallbackUnavailable');
150
- const provider = new Provider(file, `http://127.0.0.1:${address.port}/callback`, requestedAgentId, true, resource);
152
+ const provider = new Provider(file, `http://127.0.0.1:${address.port}/callback`, requestedAgentId, true, resource, options.onTokens);
151
153
  let timer;
152
154
  let callback;
153
155
  let accepted = false, finished = false;
154
156
  const failure = 'Approval was not accepted. Return to your terminal and retry Connect.';
155
- const cleanup = () => { clearTimeout(timer); server.close(); };
157
+ const cleanup = () => { clearTimeout(timer); options.signal?.removeEventListener('abort', cancel); server.close(); };
158
+ let rejectCode = () => undefined;
159
+ const cancel = () => { fail(); rejectCode(new Error('ApprovalCancelled')); };
156
160
  const fail = () => {
157
161
  finished = true;
158
162
  if (callback && !callback.writableEnded) {
@@ -162,6 +166,7 @@ export async function openOAuth(profile, requestedAgentId, resource = RESOURCE,
162
166
  cleanup();
163
167
  };
164
168
  const code = new Promise((resolve, reject) => {
169
+ rejectCode = reject;
165
170
  timer = setTimeout(() => {
166
171
  console.error({ error_class: 'Error', cause: 'ApprovalTimeout', location: 'mcp/src/oauth-client.ts:openOAuth:approvalTimeout' });
167
172
  fail();
@@ -180,6 +185,14 @@ export async function openOAuth(profile, requestedAgentId, resource = RESOURCE,
180
185
  res.end(failure);
181
186
  return;
182
187
  }
188
+ const validEnvelope = !finished && !accepted && req.method === 'GET' && req.headers.host === `127.0.0.1:${address.port}` && url.pathname === '/callback' && url.searchParams.getAll('state').length === 1 && provider.validState(url.searchParams.get('state'));
189
+ if (validEnvelope && url.searchParams.getAll('error').length === 1 && url.searchParams.get('error') === 'access_denied' && !url.searchParams.has('code')) {
190
+ res.writeHead(400);
191
+ res.end(failure);
192
+ fail();
193
+ reject(new Error('ApprovalDenied'));
194
+ return;
195
+ }
183
196
  const value = url.searchParams.get('code');
184
197
  if (finished || accepted || req.method !== 'GET' || req.headers.host !== `127.0.0.1:${address.port}` || url.pathname !== '/callback'
185
198
  || url.searchParams.getAll('state').length !== 1 || url.searchParams.getAll('code').length !== 1
@@ -195,6 +208,9 @@ export async function openOAuth(profile, requestedAgentId, resource = RESOURCE,
195
208
  resolve(value);
196
209
  });
197
210
  });
211
+ options.signal?.addEventListener('abort', cancel, { once: true });
212
+ if (options.signal?.aborted)
213
+ cancel();
198
214
  const complete = ({ agentId, workspaceId }) => {
199
215
  if (!accepted)
200
216
  return; // Cached-token launch has no browser response.
@@ -212,7 +228,7 @@ export async function openOAuth(profile, requestedAgentId, resource = RESOURCE,
212
228
  // A cached-token success never awaits the callback; prevent an unhandled
213
229
  // rejection while its timer is being cancelled in finally.
214
230
  void code.catch(() => undefined);
215
- const transport = new StreamableHTTPClientTransport(new URL(resource), { authProvider: provider, fetch: safeFetch(resource) });
231
+ const transport = new StreamableHTTPClientTransport(new URL(resource), { authProvider: provider, fetch: async (input, init) => safeFetch(resource)(input, { ...init, signal: options.signal ? AbortSignal.any([options.signal, ...init?.signal ? [init.signal] : []]) : init?.signal }) });
216
232
  let client = new Client({ name: 'agentmesh-terminal', version: '0.2.2' });
217
233
  try {
218
234
  // A new callback port needs its own registration. Valid cached grants have
@@ -224,10 +240,13 @@ export async function openOAuth(profile, requestedAgentId, resource = RESOURCE,
224
240
  catch (error) {
225
241
  if (!(error instanceof UnauthorizedError) || !provider.authorizationStarted)
226
242
  throw error;
227
- await transport.finishAuth(await code);
243
+ const authorizationCode = await code;
244
+ options.signal?.throwIfAborted();
245
+ await options.onExchange?.();
246
+ await transport.finishAuth(authorizationCode);
228
247
  await client.close();
229
248
  client = new Client({ name: 'agentmesh-terminal', version: '0.2.2' });
230
- await client.connect(new StreamableHTTPClientTransport(new URL(resource), { authProvider: provider, fetch: safeFetch(resource) }));
249
+ await client.connect(new StreamableHTTPClientTransport(new URL(resource), { authProvider: provider, fetch: async (input, init) => safeFetch(resource)(input, { ...init, signal: options.signal ? AbortSignal.any([options.signal, ...init?.signal ? [init.signal] : []]) : init?.signal }) }));
231
250
  }
232
251
  if (!accepted)
233
252
  cleanup();
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.6";
41
+ const SERVER_VERSION = "0.3.8";
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) {
@@ -62,6 +62,7 @@ export const CHANNEL_INSTRUCTIONS = 'Messages from agentmesh.md arrive as <chann
62
62
  function localStateRemedy(error) {
63
63
  const reason = error instanceof Error ? error.message : '';
64
64
  switch (reason) {
65
+ case 'AgyWakeUnavailable': return 'AgentMesh wakes are Off. Restart agy in this folder, send your first message and approve the startup command.';
65
66
  case 'ConnectRequiredForFolder': return 'AgentMesh folder is offline; run Connect in this folder.';
66
67
  case 'RuntimeRestartRequired': return RESTART_RUNTIME;
67
68
  case 'NativeSessionIdentityUnavailable': return 'AgentMesh wake listener is not active for this session yet. In Codex, trust the AgentMesh hooks in /hooks and send a message first.';
@@ -114,8 +115,10 @@ export function buildServer(opts = {}) {
114
115
  };
115
116
  }
116
117
  let args = request.params.arguments ?? {};
118
+ const root = request.params._meta?.['antigravity.google/root_conversation_id'];
119
+ const context = typeof root === 'string' && /^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/i.test(root) ? { rootConversationId: root.toLowerCase() } : {};
117
120
  try {
118
- args = await opts.prepareArguments?.(tool.name, args) ?? args;
121
+ args = await opts.prepareArguments?.(tool.name, args, context) ?? args;
119
122
  }
120
123
  catch (error) {
121
124
  opts.onToolError?.(error);
@@ -138,7 +141,7 @@ export function buildServer(opts = {}) {
138
141
  // AbortSignal — now surfaced at `ctx.mcpReq.signal` — so a client
139
142
  // cancellation aborts the in-flight upstream request immediately
140
143
  // (no lingering socket, no attempt 2).
141
- const result = opts.dispatch ? await opts.dispatch(tool.name, args, ctx.mcpReq.signal) : (await tool.run(args, ctx.mcpReq.signal));
144
+ const result = opts.dispatch ? await opts.dispatch(tool.name, args, ctx.mcpReq.signal, context) : (await tool.run(args, ctx.mcpReq.signal));
142
145
  // ^ tools.ts still types its results against the 1.x SDK's
143
146
  // CallToolResult (Seam A owns that file). The value is a plain
144
147
  // `{content:[{type:"text",…}], structuredContent?, isError?}` object
@@ -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 )?(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+\)/);
6
+ const frame = (error instanceof Error ? error.stack : '')?.match(/at (?:async )?(agyConnect|removeAgy|agyCall|agyProxy|agyHook|agyMonitor|agentapi|activeFolder|wakeDirectory|loadBinding|saveBinding|newBinding|folderOption|principal|directory|root|profile|readPrivate|credentials|install|enrollment|lifecycle|snapshot|replace|configured|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|hooks|monitor)|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,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentmesh-md/mcp-server",
3
- "version": "0.3.6",
3
+ "version": "0.3.8",
4
4
  "mcpName": "md.agentmesh/agentmesh",
5
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",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentmesh",
3
- "version": "0.3.6",
3
+ "version": "0.3.8",
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
- "24a87a70a4fd8acd79e2911e9a3863df5f83abe559e30713ac71bfb0c6e357ad"
12
+ "7831a92a81435fc50de845bc9b47410e91445ff4612933aaef2fdde95b48a0a6"
13
13
  ]
14
14
  }
15
15
  },
@@ -1,4 +1,4 @@
1
- # AgentMesh existing-session plugin (0.3.6 candidate)
1
+ # AgentMesh existing-session plugin (0.3.8 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.
@@ -7,6 +7,7 @@ marketplace is live.
7
7
 
8
8
  - Claude Code: AgentMesh connection saved. Quit Claude Code and start it again to load AgentMesh tools and wakes.
9
9
  - Codex: existing trusted session listeners refresh automatically. For a first connection, review and trust AgentMesh in `/hooks`, then send the first message.
10
+ - agy: run Connect in the folder, start or restart agy there, then send your first message and normally approve the AgentMesh startup command. Saved approval alone leaves Wakes Off; On requires transport and a completed model wake. Existing 037 folders reuse their saved agent and OAuth profile.
10
11
 
11
12
  Atlas may use `/reload-plugins` for the separate operator-assisted Claude Code
12
13
  same-session upgrade proof. This does not make Claude Code upgrades automatic.
@@ -33,7 +34,7 @@ Legacy stdio connections outside this plugin retain their existing contract.
33
34
  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
35
 
35
36
  Npm publication alone does not replace an installed plugin or already-loaded
36
- modules. For the coordinated 0.3.6 mesh install, Atlas reconnects every connected
37
+ modules. For the coordinated 0.3.8 mesh install, Atlas reconnects every connected
37
38
  seat in its actual workspace with its existing agent/workspace IDs, then performs
38
39
  the native activation above and verifies whoami and the wake probe. Atlas owns
39
40
  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
- "24a87a70a4fd8acd79e2911e9a3863df5f83abe559e30713ac71bfb0c6e357ad"
11
+ "7831a92a81435fc50de845bc9b47410e91445ff4612933aaef2fdde95b48a0a6"
12
12
  ]
13
13
  }
14
14
  }
@@ -1,7 +1,7 @@
1
1
  [
2
2
  {
3
- "name": "agentmesh-wake-24a87a70a4fd8acd79e2",
4
- "command": "node \"${CLAUDE_PLUGIN_ROOT}/server/lib/agentmesh-mcp.js\" plugin-monitor claude 24a87a70a4fd8acd79e2911e9a3863df5f83abe559e30713ac71bfb0c6e357ad",
3
+ "name": "agentmesh-wake-7831a92a81435fc50de8",
4
+ "command": "node \"${CLAUDE_PLUGIN_ROOT}/server/lib/agentmesh-mcp.js\" plugin-monitor claude 7831a92a81435fc50de845bc9b47410e91445ff4612933aaef2fdde95b48a0a6",
5
5
  "description": "AgentMesh offers for this existing session"
6
6
  }
7
7
  ]
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
3
3
  "name": "agentmesh",
4
- "version": "0.3.6",
4
+ "version": "0.3.8",
5
5
  "description": "AgentMesh tools and wake delivery in your existing session."
6
6
  }
@@ -1 +1 @@
1
- {"digest":"24a87a70a4fd8acd79e2911e9a3863df5f83abe559e30713ac71bfb0c6e357ad"}
1
+ {"digest":"7831a92a81435fc50de845bc9b47410e91445ff4612933aaef2fdde95b48a0a6"}