Skip to content

Commit f163d12

Browse files
committed
refactor(mcp): centralize tool filter policy
1 parent 8f23e68 commit f163d12

9 files changed

Lines changed: 125 additions & 141 deletions

‎src/agents/agent-bundle-mcp-filter.test.ts‎

Lines changed: 0 additions & 22 deletions
This file was deleted.

‎src/agents/agent-bundle-mcp-filter.ts‎

Lines changed: 0 additions & 37 deletions
This file was deleted.

‎src/agents/agent-bundle-mcp-materialize.ts‎

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import { normalizeLowercaseStringOrEmpty } from "@openclaw/normalization-core/st
77
import type { OpenClawConfig } from "../config/types.openclaw.js";
88
import { logWarn } from "../logger.js";
99
import { getPluginToolMeta, setPluginToolMeta, type PluginToolMcpMeta } from "../plugins/tools.js";
10-
import { matchesMcpToolFilterPattern } from "./agent-bundle-mcp-filter.js";
1110
import {
1211
buildSafeToolName,
1312
normalizeReservedToolNames,
@@ -22,6 +21,7 @@ import type {
2221
SessionMcpRuntime,
2322
} from "./agent-bundle-mcp-types.js";
2423
import { mcpContentBlockToAgentContent } from "./mcp-content.js";
24+
import { isMcpToolAllowed } from "./mcp-tool-filter.js";
2525
import { buildMcpAppCanvasPayload, fetchMcpAppView } from "./mcp-ui-resource.js";
2626
import type { AgentToolResult } from "./runtime/index.js";
2727
import type { AnyAgentTool } from "./tools/common.js";
@@ -210,15 +210,7 @@ function serverAllowsUtilityTool(
210210
if ((server.deniedToolNames?.includes(operation) === true) !== sessionDeniedOnly) {
211211
return false;
212212
}
213-
const include = server.toolFilter?.include ?? [];
214-
const exclude = server.toolFilter?.exclude ?? [];
215-
if (
216-
include.length > 0 &&
217-
!include.some((pattern) => matchesMcpToolFilterPattern(pattern, operation))
218-
) {
219-
return false;
220-
}
221-
return !exclude.some((pattern) => matchesMcpToolFilterPattern(pattern, operation));
213+
return isMcpToolAllowed(server.toolFilter, operation);
222214
}
223215

224216
function addMcpUtilityTool(params: {

‎src/agents/agent-bundle-mcp-runtime.ts‎

Lines changed: 6 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@ import { redactToolPayloadText } from "../logging/redact.js";
2222
import type { PluginManifestRegistry } from "../plugins/manifest-registry.js";
2323
import { runTasksWithConcurrency } from "../utils/run-with-concurrency.js";
2424
import { mergeMcpToolCatalogs } from "./agent-bundle-mcp-combined.js";
25-
import { matchesMcpToolFilterPattern } from "./agent-bundle-mcp-filter.js";
2625
import {
2726
completeDeferredSessionMcpRuntimeRetirement,
2827
disposeAllSessionMcpRuntimes,
@@ -69,6 +68,7 @@ import { createMcpJsonSchemaValidator } from "./mcp-json-schema-validator.js";
6968
import { sanitizeMcpMetadataText } from "./mcp-metadata.js";
7069
import { collectMcpPaginatedItems } from "./mcp-pagination.js";
7170
import { OpenClawStdioClientTransport } from "./mcp-stdio-transport.js";
71+
import { isMcpToolAllowed, normalizeMcpToolFilter } from "./mcp-tool-filter.js";
7272
import { resolveMcpTransport } from "./mcp-transport.js";
7373

7474
type BundleMcpSession = {
@@ -114,11 +114,6 @@ function getBundleMcpTestState(): BundleMcpTestState {
114114
return state;
115115
}
116116

117-
type McpToolSelection = {
118-
include?: readonly string[];
119-
exclude?: readonly string[];
120-
};
121-
122117
type McpServerBackoffState = {
123118
session: BundleMcpSession;
124119
failures: number;
@@ -285,14 +280,6 @@ function buildMcpClientOptions(mcpAppsEnabled: boolean): ClientOptions {
285280
return { capabilities: buildMcpClientCapabilities(mcpAppsEnabled) };
286281
}
287282

288-
function normalizeStringList(value: unknown): string[] | undefined {
289-
if (!Array.isArray(value)) {
290-
return undefined;
291-
}
292-
const entries = value.filter((entry): entry is string => typeof entry === "string");
293-
return entries.length > 0 ? entries : undefined;
294-
}
295-
296283
function normalizeToolUiVisibility(value: unknown): Array<"app" | "model"> | undefined {
297284
if (!Array.isArray(value)) {
298285
return undefined;
@@ -303,28 +290,6 @@ function normalizeToolUiVisibility(value: unknown): Array<"app" | "model"> | und
303290
return [...new Set(normalized)].toSorted();
304291
}
305292

306-
function getMcpToolSelection(rawServer: unknown): McpToolSelection {
307-
if (!isRecord(rawServer) || !isRecord(rawServer.toolFilter)) {
308-
return {};
309-
}
310-
return {
311-
include: normalizeStringList(rawServer.toolFilter.include),
312-
exclude: normalizeStringList(rawServer.toolFilter.exclude),
313-
};
314-
}
315-
316-
function shouldExposeMcpTool(selection: McpToolSelection, toolName: string): boolean {
317-
const include = selection.include ?? [];
318-
const exclude = selection.exclude ?? [];
319-
if (
320-
include.length > 0 &&
321-
!include.some((pattern) => matchesMcpToolFilterPattern(pattern, toolName))
322-
) {
323-
return false;
324-
}
325-
return !exclude.some((pattern) => matchesMcpToolFilterPattern(pattern, toolName));
326-
}
327-
328293
function summarizeServerCapabilities(capabilities: ServerCapabilities | undefined) {
329294
return {
330295
resources: capabilities?.resources
@@ -891,13 +856,15 @@ export function createSessionMcpRuntime(params: {
891856
),
892857
});
893858
failIfDisposed();
894-
const selection = getMcpToolSelection(rawServer);
859+
const toolFilter = normalizeMcpToolFilter(
860+
isRecord(rawServer) ? rawServer.toolFilter : undefined,
861+
);
895862
const denialMap = params.toolOverrides?.mcpToolsDeny;
896863
const deniedToolNames = new Set(
897864
denialMap && Object.hasOwn(denialMap, serverName) ? denialMap[serverName] : [],
898865
);
899866
const policyEligibleTools = listedTools.filter((tool) =>
900-
shouldExposeMcpTool(selection, tool.name.trim()),
867+
isMcpToolAllowed(toolFilter, tool.name.trim()),
901868
);
902869
const exposedTools = policyEligibleTools.filter((tool) => {
903870
const toolName = tool.name.trim();
@@ -922,14 +889,7 @@ export function createSessionMcpRuntime(params: {
922889
},
923890
}
924891
: {}),
925-
...(selection.include || selection.exclude
926-
? {
927-
toolFilter: {
928-
...(selection.include ? { include: [...selection.include] } : {}),
929-
...(selection.exclude ? { exclude: [...selection.exclude] } : {}),
930-
},
931-
}
932-
: {}),
892+
...(toolFilter ? { toolFilter } : {}),
933893
...(deniedToolNames.size > 0
934894
? { deniedToolNames: [...deniedToolNames].toSorted() }
935895
: {}),

‎src/agents/agent-bundle-mcp-types.ts‎

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import type {
66
} from "@modelcontextprotocol/sdk/types.js";
77
import type { TSchema } from "typebox";
88
import type { SessionToolOverrides } from "../config/sessions/types.js";
9-
import type { McpCodexToolApprovalMode } from "../config/types.mcp.js";
9+
import type { McpCodexToolApprovalMode, McpServerToolFilterConfig } from "../config/types.mcp.js";
1010
import type { OpenClawConfig } from "../config/types.openclaw.js";
1111
import type { PluginManifestRegistry } from "../plugins/manifest-registry.js";
1212
import type { McpCodexToolAnnotations } from "./mcp-codex-tool-approval.js";
@@ -40,10 +40,7 @@ export type McpServerCatalog = {
4040
};
4141
requestTimeoutMs?: number;
4242
supportsParallelToolCalls?: boolean;
43-
toolFilter?: {
44-
include?: string[];
45-
exclude?: string[];
46-
};
43+
toolFilter?: McpServerToolFilterConfig;
4744
deniedToolNames?: string[];
4845
codexApprovalMode?: McpCodexToolApprovalMode;
4946
};

‎src/agents/mcp-tool-filter.test.ts‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import { describe, expect, it } from "vitest";
2+
import { isMcpToolAllowed, normalizeMcpToolFilter } from "./mcp-tool-filter.js";
3+
4+
describe("isMcpToolAllowed", () => {
5+
it.each([
6+
["", "tool", false],
7+
["search_docs", "search_docs", true],
8+
["search_docs", "read_docs", false],
9+
["*_docs", "search_docs", true],
10+
["resources_*", "resources_read", true],
11+
["a**b***c", "axbyc", true],
12+
["a*b*c", "acb", false],
13+
])("matches %j against %j", (pattern, value, expected) => {
14+
expect(isMcpToolAllowed({ include: [pattern] }, value)).toBe(expected);
15+
});
16+
17+
it("rejects adversarial separated wildcards without regex backtracking", () => {
18+
const pattern = `${"*a".repeat(128)}*b`;
19+
const value = `${"a".repeat(10_000)}c`;
20+
expect(isMcpToolAllowed({ include: [pattern] }, value)).toBe(false);
21+
});
22+
23+
it.each([
24+
[undefined, undefined],
25+
["malformed", undefined],
26+
[{ include: "search_*", exclude: 42 }, undefined],
27+
[{ include: [] }, undefined],
28+
[{ include: [false, "search_*", null] }, { include: ["search_*"] }],
29+
[{ include: [false, null] }, undefined],
30+
[{ exclude: [false, "search_*", null] }, { exclude: ["search_*"] }],
31+
[
32+
{ include: [" *_docs "], exclude: ["admin_*"] },
33+
{ include: [" *_docs "], exclude: ["admin_*"] },
34+
],
35+
])("normalizes filter %j", (raw, expected) => {
36+
expect(normalizeMcpToolFilter(raw)).toEqual(expected);
37+
});
38+
39+
it("requires an include match and lets exclude win", () => {
40+
const filter = { include: ["*_docs"], exclude: ["search_*"] };
41+
expect(isMcpToolAllowed(filter, "read_docs")).toBe(true);
42+
expect(isMcpToolAllowed(filter, "search_docs")).toBe(false);
43+
expect(isMcpToolAllowed(filter, "read_file")).toBe(false);
44+
});
45+
});

‎src/agents/mcp-tool-filter.ts‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
import { isRecord } from "@openclaw/normalization-core/record-coerce";
2+
import { filterStringEntries } from "@openclaw/normalization-core/string-normalization";
3+
import type { McpServerToolFilterConfig } from "../config/types.mcp.js";
4+
5+
/** Match the documented MCP tool-filter glob syntax: exact text plus `*`. */
6+
function matchesMcpToolFilterPattern(pattern: string, value: string): boolean {
7+
const trimmed = pattern.trim();
8+
if (!trimmed) {
9+
return false;
10+
}
11+
if (!trimmed.includes("*")) {
12+
return trimmed === value;
13+
}
14+
15+
const parts = trimmed.split("*");
16+
const first = parts[0] ?? "";
17+
const last = parts.at(-1) ?? "";
18+
if (first && !value.startsWith(first)) {
19+
return false;
20+
}
21+
let cursor = first.length;
22+
const endBound = last ? value.length - last.length : value.length;
23+
if (last && (!value.endsWith(last) || endBound < cursor)) {
24+
return false;
25+
}
26+
27+
for (const part of parts.slice(1, -1)) {
28+
if (!part) {
29+
continue;
30+
}
31+
const index = value.indexOf(part, cursor);
32+
if (index === -1 || index + part.length > endBound) {
33+
return false;
34+
}
35+
cursor = index + part.length;
36+
}
37+
return true;
38+
}
39+
40+
/** Normalizes open-world MCP tool filters into the runtime policy shape. */
41+
export function normalizeMcpToolFilter(raw: unknown): McpServerToolFilterConfig | undefined {
42+
if (!isRecord(raw)) {
43+
return undefined;
44+
}
45+
const include = filterStringEntries(raw.include);
46+
const exclude = filterStringEntries(raw.exclude);
47+
if (include.length === 0 && exclude.length === 0) {
48+
return undefined;
49+
}
50+
return {
51+
...(include.length > 0 ? { include } : {}),
52+
...(exclude.length > 0 ? { exclude } : {}),
53+
};
54+
}
55+
56+
/** Applies the shared include-then-exclude policy. */
57+
export function isMcpToolAllowed(
58+
toolFilter: McpServerToolFilterConfig | undefined,
59+
toolName: string,
60+
): boolean {
61+
const matches = (pattern: string) => matchesMcpToolFilterPattern(pattern, toolName);
62+
return (
63+
(!toolFilter?.include?.length || toolFilter.include.some(matches)) &&
64+
!toolFilter?.exclude?.some(matches)
65+
);
66+
}

‎src/config/mcp-config.ts‎

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import { replaceConfigFile } from "./mutate.js";
1212
import { redactSensitiveArgv } from "./redact-argv.js";
1313
import { REDACTED_SENTINEL, restoreRedactedValues } from "./redact-snapshot.js";
1414
import { buildConfigSchemaCore } from "./schema.js";
15+
import type { McpServerToolFilterConfig } from "./types.mcp.js";
1516
import type { OpenClawConfig } from "./types.openclaw.js";
1617
import { validateConfigObjectWithPlugins } from "./validation.js";
1718

@@ -40,12 +41,6 @@ type McpConfigMutation = {
4041
};
4142
type McpConfigMutationHook = (mutation: McpConfigMutation) => Promise<void>;
4243

43-
/** Include/exclude tool selection stored for a configured MCP server. */
44-
type McpServerToolSelection = {
45-
include?: string[];
46-
exclude?: string[];
47-
};
48-
4944
function normalizeToolSelectionList(value: readonly string[] | undefined): string[] | undefined {
5045
if (!value) {
5146
return undefined;
@@ -206,7 +201,7 @@ async function updateConfiguredMcpServerConfig(params: {
206201
async function updateConfiguredMcpServerTools(
207202
params: {
208203
name: string;
209-
tools: McpServerToolSelection | null;
204+
tools: McpServerToolFilterConfig | null;
210205
recordIndependentOwner?: boolean;
211206
},
212207
onCommitted?: McpConfigMutationHook,

0 commit comments

Comments
 (0)