You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by "Sun-GLiang (via GitHub)" <gi...@apache.org> on 2026/09/16 07:26:01 UTC
[PR] feat(cli): isolate ACP MCP per Session (PR5 γ; stacked Draft) [maka]
Sun-GLiang opened a new pull request, #5386:
URL: https://github.com/apache/maka/pull/5386
## Scope and dependency
Third slice of #5222 / #3132. This Draft branch is stacked on β (#5385), which in turn depends on α (#5384). Do not merge γ until both predecessors land. With upstream `main` as base, GitHub temporarily displays a cumulative α+β+γ diff; after α and β merge, this PR reduces to γ. Until then, review the γ commits separately.
## γ: Session-scoped MCP
- Give each ACP Session its own stdio MCP configuration, processes and lifecycle through Host capabilities, including reconnection, retirement and release.
- Keep tool grants and admission at the authoritative Host boundary; retain the Desktop/TUI shared publication seam.
- Advance the Host protocol epoch from 154 to 155 for the capability change, with Host/Core and real SDK child-process coverage.
- Update the split validation notes; the unrelated Side Chat E2E flake remains outside these PRs.
## Verification
Full workspace `npm run build:test` and `npm run typecheck`; lint, format and ASF header checks; protocol epoch check from the original base; 152 targeted ACP/Host/Core tests; five real-SDK child-process Host/MCP tests; CLI dist suite 1121 passed, 3 skipped, 0 failed. The original #5222 is unchanged.
Refs #3132, #5222
Generated-by: Codex
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org
Re: [PR] feat(cli): isolate ACP MCP per Session (PR5 γ) [maka]
Posted by "Sun-GLiang (via GitHub)" <gi...@apache.org>.
Sun-GLiang commented on PR #5386:
URL: https://github.com/apache/maka/pull/5386#issuecomment-5762029292
Thanks for the detailed review. I rebased the PR onto current Apache main (879e0a4bc), advanced the Host compatibility epoch from 171 to 172, and pushed the follow-up as 1f7c88c80.
What changed:
- The exact lost-response-by-timeout/interruption path from P2 is not reachable in the current dispatcher: capability mutations use the connection-scoped failure path, which closes/clears the channel before the client finally block can treat a release as authoritative retirement. I did find a narrower production path with the same state-divergence consequence: client.capability.replace can commit, then the post-commit RootTurnCoordinator recovery can fail while the channel is still usable. The wrapper now logs a bounded diagnostic, requests Host drain, and returns the already-committed success result. A regression test exercises the production composition wrapper and verifies the replacement remains acknowledged.
- Session retirement now increments the coordinator revision for every retired Session, even when no scoped registration or stored Session state exists. This invalidates a provider-wide binding preview captured before retirement, so it cannot commit afterward and recreate the Session.
- Session MCP failures now report the actual operation: readiness failures use mcp.ready, while preparation failures use mcp.prepare.
I intentionally did not add a permanent pre-create tombstone. The pre-create registration is bounded by the existing per-provider Session limit and provider lifetime, and retirement now invalidates any in-flight preview. I also kept the documented session/new outcome-unknown retention behavior: without an authoritative create failure, unregistering could withdraw MCP tools from a Session that the Host actually created.
Verification:
- npm --workspace @maka/runtime-host run typecheck
- npm --workspace maka-agent run typecheck
- node --test packages/runtime-host/dist/__tests__/client-capability-session-scope.test.js (10/10)
- targeted production composition regression (1/1)
- node --test packages/cli/dist/__tests__/acp-session-mcp.test.js (14/14)
- npx biome format/lint on the touched source and test files
- node scripts/protocol-epoch-check.mjs --base upstream/main (171 -> 172)
The full npm run build:test successfully built the affected dependency chain, Runtime Host, and CLI, then stopped later in untouched @maka/ui code on existing API mismatch errors such as settledText/autoScroll/trailingAction.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org
Re: [PR] feat(cli): isolate ACP MCP per Session (PR5 γ) [maka]
Posted by "Astro-Han (via GitHub)" <gi...@apache.org>.
Astro-Han merged PR #5386:
URL: https://github.com/apache/maka/pull/5386
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org
Re: [PR] feat(cli): isolate ACP MCP per Session (PR5 γ) [maka]
Posted by "Astro-Han (via GitHub)" <gi...@apache.org>.
Astro-Han commented on code in PR #5386:
URL: https://github.com/apache/maka/pull/5386#discussion_r4056789346
##########
packages/runtime-host/src/protocol/index.ts:
##########
@@ -101,7 +101,9 @@ export const RUNTIME_HOST_REGISTRATION_SCHEMA_VERSION = 1 as const;
export const RUNTIME_HOST_PROTOCOL_VERSION = 0 as const;
// Increment when the same protocol version no longer guarantees safe Client-Host
// interoperability. Mismatches are rejected before domain commands are admitted.
-export const RUNTIME_HOST_COMPATIBILITY_EPOCH = 166 as const;
+export const RUNTIME_HOST_COMPATIBILITY_EPOCH = 167 as const;
Review Comment:
**P1 — epoch collision, merge-blocker.** `main` is already at **168** (167 was taken by #5468 removing `turn.regenerate`). This PR claims 167. Either merge resolution trips `protocol-epoch-check.mjs`: staying at 167 gives `headEpoch < baseEpoch`; bumping to 168 puts this PR's incompatible `client-capability` changes (`sessionId`, `admission:'mcp'`) on an epoch base already saw → rejected. Rebase onto current main and take **169**.
##########
packages/runtime-host/src/server/client-capability-coordinator.ts:
##########
@@ -961,16 +1010,41 @@ export class HostClientCapabilityCoordinator implements ClientCapabilityService
},
};
}
- const previous = provider.current;
+ const previous = this.#currentRegistration(provider, registration.sessionId);
const previousConnectionId = provider.activeConnectionId;
- if (previousConnectionId && previousConnectionId !== context.connectionId) {
- const previousConnection = this.#connections.get(previousConnectionId);
- if (previousConnection) previousConnection.superseded = true;
- this.#invocations.releaseConnection(previousConnectionId);
+ if (registration.sessionId !== undefined) {
+ provider.sessionRegistrations.set(registration.sessionId, registration);
Review Comment:
**P2 — `sessionRegistrations` has no bound, and `sessionId` is fully client-controlled.** Every other dimension of this protocol has a hard cap (offers 32, tools 256, manifest 56KiB), but a connection holding `canPublishClientCapabilities` can loop `client.capability.replace` with fabricated `sessionId`s — each pins a ≤56KiB frozen manifest plus registration entry until disconnect, and `retireSessions` only cleans *real* session ids so forged ones never release. Host memory grows unboundedly within a connection. ③ attacker-controlled input. Fix: cap `provider.sessionRegistrations.size` (allowing replace on existing ids) or validate the sessionId is a live session.
##########
packages/cli/src/acp/session-mcp.ts:
##########
@@ -0,0 +1,227 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { isAbsolute } from 'node:path';
+import { RequestError, type NewSessionRequest } from '@agentclientprotocol/sdk';
+import { MCP_CONFIG_VERSION, type McpConfigFile } from '@maka/core/mcp';
+import { McpClientManager } from '@maka/mcp';
+import { normalizeMcpConfig } from '@maka/storage/mcp-config-store';
+import type {
+ RuntimeHostConnectionAvailability,
+ RuntimeHostReconnectingConnection,
+} from '@maka/runtime-host/client';
+import { abortable } from '@maka/runtime-host/client';
+import { createMcpCapabilityProvider } from '../mcp-capability-provider.js';
+import { McpCapabilityPublication } from '../mcp-capability-publication.js';
+
+export type AcpMcpConnection = Pick<
+ RuntimeHostReconnectingConnection,
+ 'replaceClientCapabilities' | 'unregisterClientCapabilities' | 'subscribeConnectionAvailability'
+>;
+
+/** Validates before any process or Host work; never writes a user MCP configuration. */
+export function createAcpMcpConfig(params: NewSessionRequest): McpConfigFile {
+ const servers: Record<string, unknown> = Object.create(null);
+ if (!Array.isArray(params.mcpServers)) throw invalidMcpInput('invalid_servers');
+ for (const server of params.mcpServers) {
+ if (!server || typeof server !== 'object' || 'type' in server || !('command' in server)) {
+ throw invalidMcpInput('unsupported_transport');
+ }
+ if (typeof server.name !== 'string' || Object.hasOwn(servers, server.name)) {
+ throw invalidMcpInput('duplicate_or_invalid_name');
+ }
+ if (
+ typeof server.command !== 'string' ||
+ !isAbsolute(server.command) ||
+ server.command.includes('\0')
+ ) {
+ throw invalidMcpInput('command_must_be_absolute');
+ }
+ if (
+ !Array.isArray(server.args) ||
+ server.args.some((arg) => typeof arg !== 'string' || arg.includes('\0'))
+ ) {
+ throw invalidMcpInput('invalid_arguments');
+ }
+ if (!Array.isArray(server.env)) throw invalidMcpInput('invalid_environment');
+ const env: Record<string, string> = Object.create(null);
+ for (const variable of server.env) {
+ if (
+ !variable ||
+ typeof variable.name !== 'string' ||
+ variable.name.length === 0 ||
+ variable.name.includes('\0') ||
+ variable.name.includes('=') ||
+ Object.hasOwn(env, variable.name) ||
+ typeof variable.value !== 'string' ||
+ variable.value.includes('\0')
+ ) {
+ throw invalidMcpInput('duplicate_or_invalid_environment');
+ }
+ env[variable.name] = variable.value;
+ }
+ servers[server.name] = {
+ command: server.command,
+ args: server.args,
+ env,
+ cwd: params.cwd,
+ protocol: 'auto',
+ };
+ }
+ try {
+ return normalizeMcpConfig({ version: MCP_CONFIG_VERSION, mcpServers: servers });
+ } catch {
+ throw invalidMcpInput('invalid_configuration');
+ }
+}
+
+/** Owns one Session's in-memory MCP processes and publication on the shared Host connection. */
+export class AcpSessionMcp {
+ readonly #sessionId: string;
+ readonly #config: McpConfigFile;
+ readonly #manager = new McpClientManager({
+ clientName: 'maka-acp',
+ excludedStdioEnvironmentKeys: ['MAKA_RUNTIME_HOST_ACCESS_CREDENTIAL'],
+ });
+ readonly #publication: McpCapabilityPublication;
+ readonly #unsubscribeManager: () => void;
+ readonly #unsubscribeConnection: () => void;
+ #availability: RuntimeHostConnectionAvailability | undefined;
+ #prepared = false;
+ #closed = false;
+ #authoritativelyRetired = false;
+ #closeTask: Promise<void> | undefined;
+
+ constructor(sessionId: string, config: McpConfigFile, connection: AcpMcpConnection) {
+ this.#sessionId = sessionId;
+ this.#config = config;
+ this.#publication = new McpCapabilityPublication({
+ connectionIdentity: () =>
+ this.#availability?.kind === 'connected'
+ ? this.#availability.hostEpoch + '\0' + this.#availability.connectionId
+ : undefined,
+ revision: () => this.#manager.toolSnapshot().revision,
+ createProvider: () =>
+ createMcpCapabilityProvider(this.#manager, {
+ admission: 'mcp',
+ onCurrentRegistrationRetired: () => this.#retire(),
+ }),
+ replace: (provider) => connection.replaceClientCapabilities(provider, { sessionId }),
+ unregister: () => connection.unregisterClientCapabilities({ sessionId }),
+ onState: () => undefined,
+ });
+ this.#unsubscribeManager = this.#manager.onChange(() => {
+ if (this.#prepared && !this.#closed) this.#publication.request();
+ });
+ this.#unsubscribeConnection = connection.subscribeConnectionAvailability((availability) => {
+ this.#availability = availability;
+ if (availability.kind !== 'connected') this.#publication.invalidate();
+ if (this.#prepared && !this.#closed) this.#publication.request();
+ });
+ }
+
+ async prepare(signal?: AbortSignal): Promise<void> {
+ signal?.throwIfAborted();
+ const cancel = () => {
+ void this.close().catch(() => undefined);
+ };
+ signal?.addEventListener('abort', cancel, { once: true });
+ try {
+ await this.#manager.sync(this.#config);
+ signal?.throwIfAborted();
+ this.#assertConnected();
+ this.#prepared = true;
+ await this.ready(signal);
+ } catch (error) {
+ await this.close().catch(() => undefined);
+ if (error instanceof RequestError) throw error;
+ throw mcpUnavailable(this.#sessionId, 'mcp_preparation_failed');
+ } finally {
+ signal?.removeEventListener('abort', cancel);
+ }
+ }
+
+ async ready(signal?: AbortSignal): Promise<void> {
+ signal?.throwIfAborted();
+ this.#assertConnected();
+ const state = await abortable(() => this.#publication.settle(), signal);
+ signal?.throwIfAborted();
+ this.#assertConnected();
+ if (state !== 'published' && state !== 'not_published') {
+ throw mcpUnavailable(this.#sessionId, 'mcp_publication_failed');
+ }
+ }
+
+ close(): Promise<void> {
+ return this.#close(true);
+ }
+
+ #retire(): Promise<void> {
+ this.#authoritativelyRetired = true;
+ return this.#close(false);
+ }
+
+ #close(unregister: boolean): Promise<void> {
+ if (this.#closeTask) return this.#closeTask;
+ this.#closed = true;
+ this.#unsubscribeManager();
+ this.#unsubscribeConnection();
+ const managerClose = this.#manager.close();
+ this.#closeTask = (async () => {
+ try {
+ try {
+ await (unregister ? this.#publication.close() : this.#publication.retire());
+ } catch (error) {
+ // Session retirement is authoritative. If it wins the race with a local
+ // unregister, the obsolete unregister may reject even though withdrawal
+ // has already completed on the Host.
+ if (!this.#authoritativelyRetired) throw error;
+ }
+ } finally {
+ await managerClose;
+ }
+ })();
+ return this.#closeTask;
+ }
+
+ #assertConnected(): void {
+ if (
+ this.#closed ||
Review Comment:
**P2 — one dead server wedges the entire Session.** After any configured server flips `disconnected`, every prompt fails here with `mcp_not_ready` — even for conversations that would only use built-in tools — and there is no reconnect path on the ACP side (`manager.reconnect()` exists but nothing in `acp/` calls it). Suggest bounded reconnect here, or relax the gate to "current snapshot published" (a dead server's tools are already withdrawn by the publication layer), or at least a distinguishable error code.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org
Re: [PR] feat(cli): isolate ACP MCP per Session (PR5 γ) [maka]
Posted by "likun666661 (via GitHub)" <gi...@apache.org>.
likun666661 commented on PR #5386:
URL: https://github.com/apache/maka/pull/5386#issuecomment-5773375300
Review conclusion: the current implementation addresses the core ACP Session-scoped MCP isolation problem: per-Session MCP lifecycle, capability publication, tool selection, grants, invocation, reconnect, crash withdrawal, and retirement are covered. The earlier epoch collision, unbounded registration, dead-server session wedge, and lost registration response issues have been addressed.
Non-blocking note: cleanup guarantees cover the direct MCP child process; wrapper-spawned descendants may outlive the Session. This limitation is documented and can be handled separately.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org
Re: [PR] feat(cli): isolate ACP MCP per Session (PR5 γ) [maka]
Posted by "Sun-GLiang (via GitHub)" <gi...@apache.org>.
Sun-GLiang commented on code in PR #5386:
URL: https://github.com/apache/maka/pull/5386#discussion_r4056953709
##########
packages/runtime-host/src/protocol/index.ts:
##########
@@ -101,7 +101,9 @@ export const RUNTIME_HOST_REGISTRATION_SCHEMA_VERSION = 1 as const;
export const RUNTIME_HOST_PROTOCOL_VERSION = 0 as const;
// Increment when the same protocol version no longer guarantees safe Client-Host
// interoperability. Mismatches are rejected before domain commands are admitted.
-export const RUNTIME_HOST_COMPATIBILITY_EPOCH = 166 as const;
+export const RUNTIME_HOST_COMPATIBILITY_EPOCH = 167 as const;
Review Comment:
Thanks, agreed. I rebased γ onto `main` at `64f5e83de` and advanced the Host compatibility epoch to **169** in `2e37db52e`. The protocol epoch guard reports `168 -> 169`, and the GitHub `test` check now passes.
##########
packages/runtime-host/src/server/client-capability-coordinator.ts:
##########
@@ -961,16 +1010,41 @@ export class HostClientCapabilityCoordinator implements ClientCapabilityService
},
};
}
- const previous = provider.current;
+ const previous = this.#currentRegistration(provider, registration.sessionId);
const previousConnectionId = provider.activeConnectionId;
- if (previousConnectionId && previousConnectionId !== context.connectionId) {
- const previousConnection = this.#connections.get(previousConnectionId);
- if (previousConnection) previousConnection.superseded = true;
- this.#invocations.releaseConnection(previousConnectionId);
+ if (registration.sessionId !== undefined) {
+ provider.sessionRegistrations.set(registration.sessionId, registration);
Review Comment:
Agreed. `client.capability.replace` now caps each provider at **64** Session registration slots while still allowing replacement of an existing slot and reuse after unregister. Checking for an already-live Session would reject the intended ACP flow, which publishes capabilities before Host `session.create`. I also put `retireSessions` in the capability mutation queue, so a queued replacement cannot re-pin a retired slot. Both boundaries have regression tests in `2e37db52e`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org
Re: [PR] feat(cli): isolate ACP MCP per Session (PR5 γ) [maka]
Posted by "Sun-GLiang (via GitHub)" <gi...@apache.org>.
Sun-GLiang commented on code in PR #5386:
URL: https://github.com/apache/maka/pull/5386#discussion_r4056954064
##########
packages/cli/src/acp/session-mcp.ts:
##########
@@ -0,0 +1,227 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { isAbsolute } from 'node:path';
+import { RequestError, type NewSessionRequest } from '@agentclientprotocol/sdk';
+import { MCP_CONFIG_VERSION, type McpConfigFile } from '@maka/core/mcp';
+import { McpClientManager } from '@maka/mcp';
+import { normalizeMcpConfig } from '@maka/storage/mcp-config-store';
+import type {
+ RuntimeHostConnectionAvailability,
+ RuntimeHostReconnectingConnection,
+} from '@maka/runtime-host/client';
+import { abortable } from '@maka/runtime-host/client';
+import { createMcpCapabilityProvider } from '../mcp-capability-provider.js';
+import { McpCapabilityPublication } from '../mcp-capability-publication.js';
+
+export type AcpMcpConnection = Pick<
+ RuntimeHostReconnectingConnection,
+ 'replaceClientCapabilities' | 'unregisterClientCapabilities' | 'subscribeConnectionAvailability'
+>;
+
+/** Validates before any process or Host work; never writes a user MCP configuration. */
+export function createAcpMcpConfig(params: NewSessionRequest): McpConfigFile {
+ const servers: Record<string, unknown> = Object.create(null);
+ if (!Array.isArray(params.mcpServers)) throw invalidMcpInput('invalid_servers');
+ for (const server of params.mcpServers) {
+ if (!server || typeof server !== 'object' || 'type' in server || !('command' in server)) {
+ throw invalidMcpInput('unsupported_transport');
+ }
+ if (typeof server.name !== 'string' || Object.hasOwn(servers, server.name)) {
+ throw invalidMcpInput('duplicate_or_invalid_name');
+ }
+ if (
+ typeof server.command !== 'string' ||
+ !isAbsolute(server.command) ||
+ server.command.includes('\0')
+ ) {
+ throw invalidMcpInput('command_must_be_absolute');
+ }
+ if (
+ !Array.isArray(server.args) ||
+ server.args.some((arg) => typeof arg !== 'string' || arg.includes('\0'))
+ ) {
+ throw invalidMcpInput('invalid_arguments');
+ }
+ if (!Array.isArray(server.env)) throw invalidMcpInput('invalid_environment');
+ const env: Record<string, string> = Object.create(null);
+ for (const variable of server.env) {
+ if (
+ !variable ||
+ typeof variable.name !== 'string' ||
+ variable.name.length === 0 ||
+ variable.name.includes('\0') ||
+ variable.name.includes('=') ||
+ Object.hasOwn(env, variable.name) ||
+ typeof variable.value !== 'string' ||
+ variable.value.includes('\0')
+ ) {
+ throw invalidMcpInput('duplicate_or_invalid_environment');
+ }
+ env[variable.name] = variable.value;
+ }
+ servers[server.name] = {
+ command: server.command,
+ args: server.args,
+ env,
+ cwd: params.cwd,
+ protocol: 'auto',
+ };
+ }
+ try {
+ return normalizeMcpConfig({ version: MCP_CONFIG_VERSION, mcpServers: servers });
+ } catch {
+ throw invalidMcpInput('invalid_configuration');
+ }
+}
+
+/** Owns one Session's in-memory MCP processes and publication on the shared Host connection. */
+export class AcpSessionMcp {
+ readonly #sessionId: string;
+ readonly #config: McpConfigFile;
+ readonly #manager = new McpClientManager({
+ clientName: 'maka-acp',
+ excludedStdioEnvironmentKeys: ['MAKA_RUNTIME_HOST_ACCESS_CREDENTIAL'],
+ });
+ readonly #publication: McpCapabilityPublication;
+ readonly #unsubscribeManager: () => void;
+ readonly #unsubscribeConnection: () => void;
+ #availability: RuntimeHostConnectionAvailability | undefined;
+ #prepared = false;
+ #closed = false;
+ #authoritativelyRetired = false;
+ #closeTask: Promise<void> | undefined;
+
+ constructor(sessionId: string, config: McpConfigFile, connection: AcpMcpConnection) {
+ this.#sessionId = sessionId;
+ this.#config = config;
+ this.#publication = new McpCapabilityPublication({
+ connectionIdentity: () =>
+ this.#availability?.kind === 'connected'
+ ? this.#availability.hostEpoch + '\0' + this.#availability.connectionId
+ : undefined,
+ revision: () => this.#manager.toolSnapshot().revision,
+ createProvider: () =>
+ createMcpCapabilityProvider(this.#manager, {
+ admission: 'mcp',
+ onCurrentRegistrationRetired: () => this.#retire(),
+ }),
+ replace: (provider) => connection.replaceClientCapabilities(provider, { sessionId }),
+ unregister: () => connection.unregisterClientCapabilities({ sessionId }),
+ onState: () => undefined,
+ });
+ this.#unsubscribeManager = this.#manager.onChange(() => {
+ if (this.#prepared && !this.#closed) this.#publication.request();
+ });
+ this.#unsubscribeConnection = connection.subscribeConnectionAvailability((availability) => {
+ this.#availability = availability;
+ if (availability.kind !== 'connected') this.#publication.invalidate();
+ if (this.#prepared && !this.#closed) this.#publication.request();
+ });
+ }
+
+ async prepare(signal?: AbortSignal): Promise<void> {
+ signal?.throwIfAborted();
+ const cancel = () => {
+ void this.close().catch(() => undefined);
+ };
+ signal?.addEventListener('abort', cancel, { once: true });
+ try {
+ await this.#manager.sync(this.#config);
+ signal?.throwIfAborted();
+ this.#assertConnected();
+ this.#prepared = true;
+ await this.ready(signal);
+ } catch (error) {
+ await this.close().catch(() => undefined);
+ if (error instanceof RequestError) throw error;
+ throw mcpUnavailable(this.#sessionId, 'mcp_preparation_failed');
+ } finally {
+ signal?.removeEventListener('abort', cancel);
+ }
+ }
+
+ async ready(signal?: AbortSignal): Promise<void> {
+ signal?.throwIfAborted();
+ this.#assertConnected();
+ const state = await abortable(() => this.#publication.settle(), signal);
+ signal?.throwIfAborted();
+ this.#assertConnected();
+ if (state !== 'published' && state !== 'not_published') {
+ throw mcpUnavailable(this.#sessionId, 'mcp_publication_failed');
+ }
+ }
+
+ close(): Promise<void> {
+ return this.#close(true);
+ }
+
+ #retire(): Promise<void> {
+ this.#authoritativelyRetired = true;
+ return this.#close(false);
+ }
+
+ #close(unregister: boolean): Promise<void> {
+ if (this.#closeTask) return this.#closeTask;
+ this.#closed = true;
+ this.#unsubscribeManager();
+ this.#unsubscribeConnection();
+ const managerClose = this.#manager.close();
+ this.#closeTask = (async () => {
+ try {
+ try {
+ await (unregister ? this.#publication.close() : this.#publication.retire());
+ } catch (error) {
+ // Session retirement is authoritative. If it wins the race with a local
+ // unregister, the obsolete unregister may reject even though withdrawal
+ // has already completed on the Host.
+ if (!this.#authoritativelyRetired) throw error;
+ }
+ } finally {
+ await managerClose;
+ }
+ })();
+ return this.#closeTask;
+ }
+
+ #assertConnected(): void {
+ if (
+ this.#closed ||
Review Comment:
Agreed. Initial `prepare()` still requires every configured server to connect. For later prompts, `ready()` waits for the current capability publication to settle, so a crashed server's tools are withdrawn before the Session continues with its remaining or built-in tools. Regression tests cover both a partial withdrawal and the only server dying (complete withdrawal). The existing `RequestError.data.code` already carried `mcp_not_ready`; the availability fix removes the persistent failure path in `2e37db52e`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org
Re: [PR] feat(cli): isolate ACP MCP per Session (PR5 γ) [maka]
Posted by "Sun-GLiang (via GitHub)" <gi...@apache.org>.
Sun-GLiang commented on PR #5386:
URL: https://github.com/apache/maka/pull/5386#issuecomment-5749850901
@Astro-Han Thanks for the thorough review. I replied to the three inline findings above. Follow-up on the remaining points:
- **Wrapper-spawned processes:** I agree that descendants are not guaranteed to exit on Session close. One factual correction: the pinned `@modelcontextprotocol/client` 2.0.0 `StdioClientTransport.close()` already escalates from SIGTERM to SIGKILL for its **direct child** after a grace period. It does not kill a process group. I narrowed the ACP README's cleanup contract to direct-child transport cleanup and explicitly noted the launcher/descendant limitation. I have not added cross-platform process-tree supervision in this PR, so descendant cleanup remains an acknowledged limitation.
- **P3 retirement race:** `retireSessions` now runs in the capability mutation queue, and a regression test covers a queued `replace` followed by retirement.
- **P3 interop/IDs:** The current ACP `NewSessionRequest` requires an `mcpServers` array; this PR intentionally accepts only untagged stdio servers. The ACP publication path normalizes server/tool IDs before Host registration. The general wire decoder accepts a broader charset, which fails closed at grant decoding; I added that note to the PR description.
Commit `2e37db52e` contains the changes. Local build, typecheck, lint, format, the protocol epoch guard, 153 affected Host tests, 14 ACP MCP tests, and five real Host/ACP child-process tests passed. All current GitHub checks are green.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org