You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by zh...@apache.org on 2026/09/03 17:00:53 UTC

(maka) branch fix/desktop-mcp-capability-schema created (now 78db038674)

This is an automated email from the ASF dual-hosted git repository.

me2seeks pushed a change to branch fix/desktop-mcp-capability-schema
in repository https://gitbox.apache.org/repos/asf/maka.git


      at 78db038674 fix(desktop): chunk and degrade oversized MCP capability manifests

This branch includes the following new commits:

     new b0af27f9bb fix(runtime-host): admit Desktop MCP tools through the desktop_mcp Session Grant
     new 78db038674 fix(desktop): chunk and degrade oversized MCP capability manifests

The 2 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.



---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


(maka) 01/02: fix(runtime-host): admit Desktop MCP tools through the desktop_mcp Session Grant

Posted by zh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

me2seeks pushed a commit to branch fix/desktop-mcp-capability-schema
in repository https://gitbox.apache.org/repos/asf/maka.git

commit b0af27f9bb43074893e6fe255aeb3f83e6e36e5f
Author: me2seeks <me...@gmail.com>
AuthorDate: Fri Sep 4 00:59:42 2026 +0800

    fix(runtime-host): admit Desktop MCP tools through the desktop_mcp Session Grant
    
    managedClientCapabilityGrantTarget() only recognized Desktop Settings and
    Browser, so a managed ask-mode call to a desktop_mcp tool failed before
    admission with 'no managed admission policy'. Recognize the Desktop-owned
    desktop_mcp server identity and produce the existing desktop_mcp/mcp_tool
    grant target, reusing the generic approval, grant persistence, and prompt
    plumbing. The policy keys on the descriptor serverId so chunked offers stay
    admissible. Adds Host-level ask regressions covering
    accept-approval-admit-execute, per-tool Session Grant reuse, and the deny
    path (#4490).
---
 .../client-capability-coordinator.test.ts          | 135 +++++++++++++++++++++
 .../src/server/client-capability-coordinator.ts    |  63 ++++++----
 2 files changed, 175 insertions(+), 23 deletions(-)

diff --git a/packages/runtime-host/src/__tests__/client-capability-coordinator.test.ts b/packages/runtime-host/src/__tests__/client-capability-coordinator.test.ts
index c34e4611f8..994b5874fb 100644
--- a/packages/runtime-host/src/__tests__/client-capability-coordinator.test.ts
+++ b/packages/runtime-host/src/__tests__/client-capability-coordinator.test.ts
@@ -471,6 +471,141 @@ describe('Host Client Capability coordinator', () => {
     await coordinator.close();
   });
 
+  test('approves a trusted Desktop MCP tool once and scopes the Session Grant per tool', async () => {
+    let approvedTarget:
+      | Parameters<
+          HostClientCapabilityCoordinatorOptions['interactions']['requestClientCapabilityApproval']
+        >[0]['target']
+      | undefined;
+    let approvalCount = 0;
+    const coordinator = createCoordinator(() => undefined, {
+      interactions: {
+        requestClientCapabilityApproval: async ({ target }) => {
+          approvalCount += 1;
+          approvedTarget = target;
+          return 'allow';
+        },
+      },
+      grants: {
+        readClientCapabilitySessionGrant: async (key) =>
+          approvedTarget &&
+          approvedTarget.providerId === key.providerId &&
+          approvedTarget.contractId === key.contractId &&
+          approvedTarget.capability === key.capability &&
+          approvedTarget.scope.kind === 'mcp_tool' &&
+          key.scope.kind === 'mcp_tool' &&
+          approvedTarget.scope.serverId === key.scope.serverId &&
+          approvedTarget.scope.toolName === key.scope.toolName
+            ? { version: 1, ...key, grantedAt: 1 }
+            : undefined,
+      },
+    });
+    const sent: unknown[] = [];
+    const connection = attachAutoAdmittingConnection(
+      coordinator,
+      'connection-a',
+      () => ({ kind: 'none' }),
+      'done',
+      sent,
+    );
+    await registerSessionTools(coordinator, 'connection-a', 'registration-mcp', 'desktop_mcp', [
+      'fixture_echo',
+      'fixture_ping',
+    ]);
+    assert.deepEqual(await coordinator.bindSession('session-a', 'connection-a'), { ok: true });
+    const snapshot = coordinator.snapshotForSession('session-a');
+    assert.ok(snapshot);
+    const tools = new Map(snapshot.tools.map((tool) => [tool.displayName, tool]));
+
+    // accept -> approval -> admit -> execute: the provider is never admitted
+    // before the approval resolves.
+    const preparedEcho = await prepare(tools.get('fixture_echo'), {}, 'tool-echo');
+    assert.equal(approvalCount, 1);
+    assert.equal(approvedTarget?.capability, 'desktop_mcp');
+    assert.deepEqual(approvedTarget?.scope, {
+      kind: 'mcp_tool',
+      serverId: 'desktop_mcp',
+      toolName: 'fixture_echo',
+    });
+    assert.equal(
+      sent.some((frame) => isRecord(frame) && frame.kind === 'client.capability.admitted'),
+      false,
+    );
+    assert.deepEqual(await preparedEcho.execute(managedContext('tool-echo')), textResult('done'));
+    const admittedIndex = sent.findIndex(
+      (frame) => isRecord(frame) && frame.kind === 'client.capability.admitted',
+    );
+    const callIndex = sent.findIndex(
+      (frame) => isRecord(frame) && frame.kind === 'client.capability.call',
+    );
+    assert.ok(callIndex >= 0 && admittedIndex > callIndex);
+
+    // The persisted Session Grant covers the approved tool without a new
+    // approval...
+    const preparedEchoAgain = await prepare(tools.get('fixture_echo'), {}, 'tool-echo-again');
+    assert.equal(approvalCount, 1);
+    assert.deepEqual(
+      await preparedEchoAgain.execute(managedContext('tool-echo-again')),
+      textResult('done'),
+    );
+
+    // ...while a sibling tool under the same offer needs its own grant.
+    const preparedPing = await prepare(tools.get('fixture_ping'), {}, 'tool-ping');
+    assert.equal(approvalCount, 2);
+    assert.deepEqual(approvedTarget?.scope, {
+      kind: 'mcp_tool',
+      serverId: 'desktop_mcp',
+      toolName: 'fixture_ping',
+    });
+    assert.deepEqual(await preparedPing.execute(managedContext('tool-ping')), textResult('done'));
+
+    snapshot.release();
+    await connection.close();
+    await coordinator.close();
+  });
+
+  test('cancels a denied Desktop MCP call before admission', async () => {
+    const coordinator = createCoordinator(() => undefined, {
+      interactions: {
+        requestClientCapabilityApproval: async () => 'deny',
+      },
+      grants: {
+        readClientCapabilitySessionGrant: async () => undefined,
+      },
+    });
+    const sent: unknown[] = [];
+    const connection = attachAutoAdmittingConnection(
+      coordinator,
+      'connection-a',
+      () => ({ kind: 'none' }),
+      'done',
+      sent,
+    );
+    await registerSessionTools(coordinator, 'connection-a', 'registration-mcp', 'desktop_mcp', [
+      'fixture_echo',
+    ]);
+    assert.deepEqual(await coordinator.bindSession('session-a', 'connection-a'), { ok: true });
+    const snapshot = coordinator.snapshotForSession('session-a');
+    assert.ok(snapshot);
+
+    await assert.rejects(
+      () => prepare(snapshot.tools[0], {}, 'tool-mcp-denied'),
+      /Client Capability request was denied/u,
+    );
+    assert.equal(
+      sent.some((frame) => isRecord(frame) && frame.kind === 'client.capability.admitted'),
+      false,
+    );
+    assert.equal(
+      sent.some((frame) => isRecord(frame) && frame.kind === 'client.capability.cancel'),
+      true,
+    );
+
+    snapshot.release();
+    await connection.close();
+    await coordinator.close();
+  });
+
   test('reports capability_lost before admission and outcome_unknown after admission', async () => {
     await assertLossClassification('before_acceptance', 'capability_lost');
     await assertLossClassification('after_admission', 'outcome_unknown');
diff --git a/packages/runtime-host/src/server/client-capability-coordinator.ts b/packages/runtime-host/src/server/client-capability-coordinator.ts
index 315c440086..038a433151 100644
--- a/packages/runtime-host/src/server/client-capability-coordinator.ts
+++ b/packages/runtime-host/src/server/client-capability-coordinator.ts
@@ -66,6 +66,7 @@ import { clientCapabilityProviderId } from './client-capability-provider-id.js';
 const DEFAULT_CALL_TIMEOUT_MS = 150_000;
 const DESKTOP_BROWSER_SERVER_ID = 'desktop_browser';
 const DESKTOP_SETTINGS_SERVER_ID = 'desktop_settings';
+const DESKTOP_MCP_SERVER_ID = 'desktop_mcp';
 const DESKTOP_BROWSER_TOOLS = new Set([
   'browser_navigate',
   'browser_snapshot',
@@ -1497,32 +1498,48 @@ function managedClientCapabilityGrantTarget(
     return undefined;
   }
   if (
-    tool.offerId !== DESKTOP_BROWSER_SERVER_ID ||
-    serverId !== DESKTOP_BROWSER_SERVER_ID ||
-    !DESKTOP_BROWSER_TOOLS.has(toolName)
+    tool.offerId === DESKTOP_BROWSER_SERVER_ID &&
+    serverId === DESKTOP_BROWSER_SERVER_ID &&
+    DESKTOP_BROWSER_TOOLS.has(toolName)
   ) {
-    throw new Error(`Client Capability has no managed admission policy: ${serverId}/${toolName}`);
-  }
-  if (evidence.kind !== 'browser_url') {
-    throw new Error('Desktop Browser admission requires URL evidence');
-  }
-  let url: URL;
-  try {
-    url = new URL(evidence.url);
-  } catch {
-    throw new Error('Desktop Browser admission URL is invalid');
+    if (evidence.kind !== 'browser_url') {
+      throw new Error('Desktop Browser admission requires URL evidence');
+    }
+    let url: URL;
+    try {
+      url = new URL(evidence.url);
+    } catch {
+      throw new Error('Desktop Browser admission URL is invalid');
+    }
+    if (url.protocol !== 'http:' && url.protocol !== 'https:') {
+      throw new Error('Desktop Browser admission requires an HTTP origin');
+    }
+    return Object.freeze({
+      providerId: registration.providerId,
+      contractId,
+      serverId,
+      toolName,
+      capability: 'browser',
+      scope: Object.freeze({ kind: 'browser_origin', origin: url.origin }),
+    });
   }
-  if (url.protocol !== 'http:' && url.protocol !== 'https:') {
-    throw new Error('Desktop Browser admission requires an HTTP origin');
+  // Desktop MCP tools publish under a shared Desktop-owned server identity;
+  // chunking may spread one logical group across several offerIds, so the
+  // admission policy keys on the descriptor serverId rather than the offerId.
+  if (serverId === DESKTOP_MCP_SERVER_ID) {
+    if (evidence.kind !== 'none') {
+      throw new Error('Desktop MCP admission does not accept scope evidence');
+    }
+    return Object.freeze({
+      providerId: registration.providerId,
+      contractId,
+      serverId,
+      toolName,
+      capability: 'desktop_mcp',
+      scope: Object.freeze({ kind: 'mcp_tool', serverId, toolName }),
+    });
   }
-  return Object.freeze({
-    providerId: registration.providerId,
-    contractId,
-    serverId,
-    toolName,
-    capability: 'browser',
-    scope: Object.freeze({ kind: 'browser_origin', origin: url.origin }),
-  });
+  throw new Error(`Client Capability has no managed admission policy: ${serverId}/${toolName}`);
 }
 
 function serviceContract(serviceId: string, version: string): string {


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


(maka) 02/02: fix(desktop): chunk and degrade oversized MCP capability manifests

Posted by zh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

me2seeks pushed a commit to branch fix/desktop-mcp-capability-schema
in repository https://gitbox.apache.org/repos/asf/maka.git

commit 78db038674a2ac502de51d309e1f0e0a4f5df228
Author: me2seeks <me...@gmail.com>
AuthorDate: Fri Sep 4 00:59:43 2026 +0800

    fix(desktop): chunk and degrade oversized MCP capability manifests
    
    A desktop_mcp group beyond the 64-tool single-offer limit failed the full
    manifest decode, taking Browser, Settings, and Rive registration down with
    it. Chunk dynamic groups into stable per-offer ids while keeping the group's
    server identity, shed trailing dynamic tools when the total tool, offer, or
    byte budgets are exceeded, keep fixed groups loud when they overflow, decode
    the manifest authoritatively before it is sent, and report omissions through
    a visible diagnostic (#4490).
---
 .../src/main/__tests__/mcp-runtime-e2e.test.ts     |   7 +-
 .../runtime-host-native-capabilities.test.ts       | 183 +++++++++++++++++++++
 .../src/main/runtime-host-desktop-candidate.ts     |   1 +
 .../src/main/runtime-host-native-capabilities.ts   | 148 +++++++++++++++--
 4 files changed, 328 insertions(+), 11 deletions(-)

diff --git a/apps/desktop/src/main/__tests__/mcp-runtime-e2e.test.ts b/apps/desktop/src/main/__tests__/mcp-runtime-e2e.test.ts
index 3896f35231..a87ea2ca71 100644
--- a/apps/desktop/src/main/__tests__/mcp-runtime-e2e.test.ts
+++ b/apps/desktop/src/main/__tests__/mcp-runtime-e2e.test.ts
@@ -103,6 +103,7 @@ test('MCP tools stay bound to the connection generation that advertised them', a
       ),
       /not offered/u,
     );
+    let admissionEvidence: unknown;
     assert.deepEqual(
       await provider.call(
         {
@@ -120,7 +121,9 @@ test('MCP tools stay bound to the connection generation that advertised them', a
         },
         {
           signal: new AbortController().signal,
-          accept: async () => undefined,
+          accept: async (evidence) => {
+            admissionEvidence = evidence;
+          },
         },
       ),
       {
@@ -130,6 +133,8 @@ test('MCP tools stay bound to the connection generation that advertised them', a
         ],
       },
     );
+    // The Host managed admission policy for desktop_mcp requires this contract.
+    assert.deepEqual(admissionEvidence, { kind: 'none' });
 
     const result = await echo.impl({ value: 'runtime-e2e' }, {
       sessionId: 'session', turnId: 'turn', cwd: process.cwd(), toolCallId: 'call',
diff --git a/apps/desktop/src/main/__tests__/runtime-host-native-capabilities.test.ts b/apps/desktop/src/main/__tests__/runtime-host-native-capabilities.test.ts
index 98d97e5ba9..bb63ec3dfc 100644
--- a/apps/desktop/src/main/__tests__/runtime-host-native-capabilities.test.ts
+++ b/apps/desktop/src/main/__tests__/runtime-host-native-capabilities.test.ts
@@ -524,6 +524,189 @@ test('dispatches through the same immutable tool snapshot it advertised', async
   );
 });
 
+test('chunks a dynamic capability group beyond the single-offer tool limit', async () => {
+  const mcpTools = Array.from({ length: 65 }, (_, index) =>
+    tool(`mcp_tool_${String(index).padStart(3, '0')}`, z.object({}), async () => `tool-${index}`),
+  );
+  const provider = createDesktopNativeCapabilityProvider({
+    browserTools: [tool('browser_snapshot', z.object({}), async () => 'ok')],
+    resolveBrowserUrl: () => 'https://example.com/',
+    releaseBrowserSession() {},
+    computerUseTools: [] as never,
+    releaseComputerUseSession() {},
+    additionalGroups: () => [
+      {
+        offerId: 'desktop_mcp',
+        label: 'MCP',
+        description: 'MCP tools connected by this Desktop client.',
+        tools: mcpTools,
+        omitUnsupportedTools: true,
+      },
+    ],
+  });
+
+  assert.deepEqual(
+    provider.offers().map((offer) => [offer.offerId, offer.tools.length] as const),
+    [
+      ['desktop_browser', 1],
+      ['desktop_mcp', 64],
+      ['desktop_mcp_2', 1],
+    ],
+  );
+  // Chunked offers keep the group's server identity.
+  assert.equal(provider.offers()[2]?.tools[0]?.serverId, 'desktop_mcp');
+  assert.equal(provider.offers()[2]?.tools[0]?.name, 'mcp_tool_064');
+  assert.doesNotThrow(() =>
+    decodeClientCapabilityReplaceInput({
+      registrationId: 'registration-1',
+      offers: provider.offers(),
+    }),
+  );
+  // A tool in a later chunk dispatches through its chunk offerId.
+  assert.deepEqual(
+    await call(
+      provider,
+      capabilityFrame({
+        offerId: 'desktop_mcp_2',
+        serverId: 'desktop_mcp',
+        toolName: 'mcp_tool_064',
+        arguments: {},
+      }),
+    ),
+    { content: [{ type: 'text', text: 'tool-64' }] },
+  );
+  await provider.close();
+});
+
+test('omits trailing dynamic tools beyond the manifest tool budget and keeps fixed groups', async () => {
+  const diagnostics: string[] = [];
+  const mcpTools = Array.from({ length: 300 }, (_, index) =>
+    tool(`mcp_tool_${String(index).padStart(3, '0')}`, z.object({}), async () => 'ok'),
+  );
+  const provider = createDesktopNativeCapabilityProvider(
+    {
+      browserTools: [tool('browser_snapshot', z.object({}), async () => 'ok')],
+      resolveBrowserUrl: () => 'https://example.com/',
+      releaseBrowserSession() {},
+      computerUseTools: [] as never,
+      releaseComputerUseSession() {},
+      additionalGroups: () => [
+        {
+          offerId: 'desktop_mcp',
+          label: 'MCP',
+          description: 'MCP tools connected by this Desktop client.',
+          tools: mcpTools,
+          omitUnsupportedTools: true,
+        },
+      ],
+    },
+    { onDiagnostic: (diagnostic) => diagnostics.push(diagnostic) },
+  );
+
+  const offers = provider.offers();
+  assert.equal(offers[0]?.offerId, 'desktop_browser');
+  assert.equal(offers[0]?.tools.length, 1);
+  let toolCount = 0;
+  for (const offer of offers) toolCount += offer.tools.length;
+  assert.equal(toolCount, 256);
+  assert.equal(offers.at(-1)?.tools.at(-1)?.name, 'mcp_tool_254');
+  assert.doesNotThrow(() =>
+    decodeClientCapabilityReplaceInput({
+      registrationId: 'registration-1',
+      offers,
+    }),
+  );
+  assert.equal(diagnostics.length, 1);
+  assert.match(diagnostics[0] ?? '', /omitted 45 MCP tool/u);
+  assert.match(diagnostics[0] ?? '', /mcp_tool_255/u);
+  await provider.close();
+});
+
+test('omits trailing dynamic tools beyond the manifest byte budget', () => {
+  const diagnostics: string[] = [];
+  const mcpTools = Array.from({ length: 80 }, (_, index) => ({
+    ...tool(`mcp_tool_${String(index).padStart(3, '0')}`, z.object({}), async () => 'ok'),
+    description: `mcp_tool_${index} ${'x'.repeat(1_000)}`,
+  }));
+  const provider = createDesktopNativeCapabilityProvider(
+    {
+      browserTools: [],
+      resolveBrowserUrl: () => 'https://example.com/',
+      releaseBrowserSession() {},
+      computerUseTools: [] as never,
+      releaseComputerUseSession() {},
+      additionalGroups: () => [
+        {
+          offerId: 'desktop_mcp',
+          label: 'MCP',
+          description: 'MCP tools connected by this Desktop client.',
+          tools: mcpTools,
+          omitUnsupportedTools: true,
+        },
+      ],
+    },
+    { onDiagnostic: (diagnostic) => diagnostics.push(diagnostic) },
+  );
+
+  const offers = provider.offers();
+  const kept = offers.flatMap((offer) => offer.tools.map((descriptor) => descriptor.name));
+  assert.ok(kept.length > 0 && kept.length < 80);
+  assert.deepEqual(
+    kept,
+    mcpTools.slice(0, kept.length).map((candidate) => candidate.name),
+  );
+  assert.doesNotThrow(() =>
+    decodeClientCapabilityReplaceInput({
+      registrationId: 'registration-1',
+      offers,
+    }),
+  );
+  assert.equal(diagnostics.length, 1);
+  assert.match(diagnostics[0] ?? '', /omitted [1-9]\d* MCP tool/u);
+});
+
+test('chunks and degrades a dynamic capability group deterministically', () => {
+  const mcpTools = Array.from({ length: 70 }, (_, index) =>
+    tool(`mcp_tool_${String(index).padStart(3, '0')}`, z.object({}), async () => 'ok'),
+  );
+  const create = () =>
+    createDesktopNativeCapabilityProvider({
+      browserTools: [],
+      resolveBrowserUrl: () => 'https://example.com/',
+      releaseBrowserSession() {},
+      computerUseTools: [] as never,
+      releaseComputerUseSession() {},
+      additionalGroups: () => [
+        {
+          offerId: 'desktop_mcp',
+          label: 'MCP',
+          description: 'MCP tools connected by this Desktop client.',
+          tools: mcpTools,
+          omitUnsupportedTools: true,
+        },
+      ],
+    });
+  const first = create();
+  const second = create();
+  assert.deepEqual(first.offers(), second.offers());
+});
+
+test('fails loudly when a fixed capability group exceeds the manifest budget', () => {
+  assert.throws(
+    () =>
+      createDesktopNativeCapabilityProvider({
+        browserTools: Array.from({ length: 65 }, (_, index) =>
+          tool(`browser_tool_${index}`, z.object({}), async () => 'ok'),
+        ),
+        resolveBrowserUrl: () => 'https://example.com/',
+        releaseBrowserSession() {},
+        computerUseTools: [] as never,
+        releaseComputerUseSession() {},
+      }),
+    /Invalid Client Capability offer tools/u,
+  );
+});
+
 test('reports provider retirement once after its registration is released', async () => {
   let retirements = 0;
   const provider = createDesktopNativeCapabilityProvider(
diff --git a/apps/desktop/src/main/runtime-host-desktop-candidate.ts b/apps/desktop/src/main/runtime-host-desktop-candidate.ts
index 582e6e9fae..22e0ddfa9b 100644
--- a/apps/desktop/src/main/runtime-host-desktop-candidate.ts
+++ b/apps/desktop/src/main/runtime-host-desktop-candidate.ts
@@ -739,6 +739,7 @@ export async function createDesktopRuntimeHostCandidate(
           onComputerUseTurnUsed: watchComputerUseTurn,
           isTargetValid: deps.isTargetValid,
           onClosed: () => providers.delete(provider),
+          onDiagnostic: logLocalRuntimeHostProcessDiagnostic,
         },
       );
       providers.add(provider);
diff --git a/apps/desktop/src/main/runtime-host-native-capabilities.ts b/apps/desktop/src/main/runtime-host-native-capabilities.ts
index cefcaf7974..c6705f3dc2 100644
--- a/apps/desktop/src/main/runtime-host-native-capabilities.ts
+++ b/apps/desktop/src/main/runtime-host-native-capabilities.ts
@@ -26,6 +26,11 @@ import {
   type OAuthPresentationBackend,
 } from "@maka/runtime-host/client";
 import {
+  CLIENT_CAPABILITY_MAX_MANIFEST_BYTES,
+  CLIENT_CAPABILITY_MAX_OFFERS,
+  CLIENT_CAPABILITY_MAX_TOOLS,
+  CLIENT_CAPABILITY_MAX_TOOLS_PER_OFFER,
+  decodeClientCapabilityReplaceInput,
   decodeClientCapabilityToolDescriptor,
   type ClientCapabilityCallFrame,
   type ClientCapabilityCallResult,
@@ -43,6 +48,8 @@ import type { DesktopTargetScope } from '../shared/runtime-host-identity.js';
 const CAPABILITY_VERSION = "0";
 const BROWSER_OFFER_ID = "desktop_browser";
 const COMPUTER_USE_OFFER_ID = "desktop_computer_use";
+// Same wire length as the registrationId the Client Capability channel assigns.
+const MANIFEST_REGISTRATION_ID_PLACEHOLDER = "00000000-0000-4000-8000-000000000000";
 
 export interface DesktopCapabilityGroup {
   readonly offerId: string;
@@ -63,6 +70,7 @@ interface PreparedDesktopCapabilityGroup {
   readonly label: string;
   readonly description: string;
   readonly tools: readonly PreparedDesktopCapabilityTool[];
+  readonly omitUnsupportedTools?: boolean;
 }
 
 type NativeToolBinding = Pick<PreparedDesktopCapabilityTool, "tool">;
@@ -117,6 +125,8 @@ interface DesktopNativeCapabilityProviderOptions {
   readonly onSessionUsed?: (sessionId: string) => void;
   readonly onComputerUseTurnUsed?: (sessionId: string, turnId: string) => void;
   readonly onClosed?: () => void;
+  /** Reports a visible degradation while assembling the published manifest. */
+  readonly onDiagnostic?: (diagnostic: string) => void;
   readonly nativeSessionId?: (sessionId: string) => string;
   readonly targetScope?: DesktopTargetScope;
 }
@@ -127,11 +137,6 @@ export function createDesktopNativeCapabilityProvider(
   providerOptions: DesktopNativeCapabilityProviderOptions = {},
 ): DesktopNativeCapabilityProvider {
   const hostPathAccess = providerOptions.hostPathAccess ?? "cwd";
-  const groups = prepareCapabilityGroups(capabilityGroups(input));
-  const offers = Object.freeze(
-    groups.map((group) => capabilityOffer(group, hostPathAccess)),
-  );
-  const bindings = indexBindings(groups);
   const oauthPresentation = input.oauthPresentation
     ? createOAuthPresentationClientProvider(input.oauthPresentation)
     : undefined;
@@ -139,6 +144,31 @@ export function createDesktopNativeCapabilityProvider(
     ? input.additionalServices(requireTargetScope(providerOptions.targetScope))
     : [];
   const services = indexServices(oauthPresentation?.services?.() ?? [], additionalServices);
+  const serviceOffers = Object.freeze(
+    [...services.values()].map(({ serviceId, version }) =>
+      Object.freeze({ serviceId, version }),
+    ),
+  );
+  const groups = fitDesktopCapabilityManifest(
+    prepareCapabilityGroups(capabilityGroups(input)),
+    serviceOffers,
+    hostPathAccess,
+    providerOptions.onDiagnostic,
+  );
+  const offers = Object.freeze(
+    groups.map((group) => capabilityOffer(group, hostPathAccess)),
+  );
+  // Authoritative check: a manifest that will be sent must decode first, so a
+  // budget overrun can never fail the whole registration at the channel. An
+  // empty provider is legal and never registers.
+  if (offers.length > 0 || serviceOffers.length > 0) {
+    decodeClientCapabilityReplaceInput({
+      registrationId: MANIFEST_REGISTRATION_ID_PLACEHOLDER,
+      offers,
+      ...(serviceOffers.length === 0 ? {} : { services: serviceOffers }),
+    });
+  }
+  const bindings = indexBindings(groups);
   const releaseSessionResources = [
     input.releaseBrowserSession,
     input.releaseComputerUseSession,
@@ -165,7 +195,7 @@ export function createDesktopNativeCapabilityProvider(
 
   return {
     offers: () => offers,
-    services: () => [...services.values()].map(({ serviceId, version }) => ({ serviceId, version })),
+    services: () => [...serviceOffers],
     call: (frame, options) => {
       if (closed)
         throw new Error("Desktop native capability provider is closed");
@@ -469,10 +499,108 @@ function prepareCapabilityGroups(
       return [{ tool, descriptor }];
     });
     if (group.omitUnsupportedTools && tools.length === 0) return [];
-    return [{ ...group, tools }];
+    return chunkPreparedGroup({ ...group, tools });
   });
 }
 
+/**
+ * Split a dynamic group beyond the single-offer tool limit into stable chunks.
+ * Chunked offers keep the group's server identity, so published tool names,
+ * Session Grant scopes, and Host admission never depend on how the group was
+ * split.
+ */
+function chunkPreparedGroup(
+  group: PreparedDesktopCapabilityGroup,
+): PreparedDesktopCapabilityGroup[] {
+  if (
+    !group.omitUnsupportedTools ||
+    group.tools.length <= CLIENT_CAPABILITY_MAX_TOOLS_PER_OFFER
+  ) {
+    return [group];
+  }
+  const chunks: PreparedDesktopCapabilityGroup[] = [];
+  for (
+    let offset = 0;
+    offset < group.tools.length;
+    offset += CLIENT_CAPABILITY_MAX_TOOLS_PER_OFFER
+  ) {
+    chunks.push({
+      ...group,
+      offerId:
+        offset === 0
+          ? group.offerId
+          : `${group.offerId}_${offset / CLIENT_CAPABILITY_MAX_TOOLS_PER_OFFER + 1}`,
+      tools: group.tools.slice(offset, offset + CLIENT_CAPABILITY_MAX_TOOLS_PER_OFFER),
+    });
+  }
+  return chunks;
+}
+
+/**
+ * Fit the assembled manifest to the Client Capability budgets before it is
+ * sent. Fixed capability groups are never degraded: if they alone exceed a
+ * budget the registration must fail loudly. Dynamic (omittable) groups shed
+ * their trailing tools instead, and the omission is reported.
+ */
+function fitDesktopCapabilityManifest(
+  groups: readonly PreparedDesktopCapabilityGroup[],
+  services: readonly ClientCapabilityServiceOffer[],
+  hostPathAccess: ClientCapabilityHostPathAccess,
+  onDiagnostic?: (diagnostic: string) => void,
+): PreparedDesktopCapabilityGroup[] {
+  const fitting = groups.map((group) => ({ group, tools: [...group.tools] }));
+  const omitted: string[] = [];
+  const assemble = (): PreparedDesktopCapabilityGroup[] =>
+    fitting
+      .filter((entry) => entry.tools.length > 0)
+      .map((entry) => ({ ...entry.group, tools: entry.tools }));
+  while (!manifestFitsBudget(assemble(), services, hostPathAccess)) {
+    let index = fitting.length - 1;
+    while (
+      index >= 0 &&
+      (!fitting[index]?.group.omitUnsupportedTools || fitting[index]?.tools.length === 0)
+    ) {
+      index -= 1;
+    }
+    const entry = fitting[index];
+    if (!entry) {
+      throw new Error(
+        "Desktop fixed capability groups exceed the Client Capability manifest budget",
+      );
+    }
+    const dropped = entry.tools.pop();
+    if (dropped) omitted.push(dropped.descriptor.name);
+  }
+  if (omitted.length > 0) {
+    const names = omitted.reverse();
+    const shown = names.slice(0, 8).join(", ");
+    onDiagnostic?.(
+      `Desktop omitted ${names.length} MCP tool(s) beyond the Client Capability manifest budget: ${shown}${names.length > 8 ? `, +${names.length - 8} more` : ""}`,
+    );
+  }
+  return assemble();
+}
+
+function manifestFitsBudget(
+  groups: readonly PreparedDesktopCapabilityGroup[],
+  services: readonly ClientCapabilityServiceOffer[],
+  hostPathAccess: ClientCapabilityHostPathAccess,
+): boolean {
+  if (groups.length > CLIENT_CAPABILITY_MAX_OFFERS) return false;
+  const offers = groups.map((group) => capabilityOffer(group, hostPathAccess));
+  let toolCount = 0;
+  for (const offer of offers) toolCount += offer.tools.length;
+  if (toolCount > CLIENT_CAPABILITY_MAX_TOOLS) return false;
+  const manifest = {
+    registrationId: MANIFEST_REGISTRATION_ID_PLACEHOLDER,
+    offers,
+    ...(services.length === 0 ? {} : { services }),
+  };
+  return (
+    Buffer.byteLength(JSON.stringify(manifest), "utf8") <= CLIENT_CAPABILITY_MAX_MANIFEST_BYTES
+  );
+}
+
 function capabilityToolDescriptor(
   offerId: string,
   tool: MakaTool,
@@ -547,11 +675,11 @@ function indexBindings(
 ): Map<string, NativeToolBinding> {
   const bindings = new Map<string, NativeToolBinding>();
   for (const group of groups) {
-    for (const { tool } of group.tools) {
+    for (const { tool, descriptor } of group.tools) {
       const key = bindingKey({
         offerId: group.offerId,
-        serverId: group.offerId,
-        toolName: tool.name,
+        serverId: descriptor.serverId,
+        toolName: descriptor.name,
       });
       if (bindings.has(key)) {
         throw new Error(


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org