feat(mcp): support tool-level directTools array and 3-state UI configuration (#297)

* feat(mcp): support tool-level directTools array and 3-state UI configuration

* refactor(mcp): refine tool hint explanation and separate server instructions block

* style(mcp): display tool count in header title and split option hints into 3 lines

* style(mcp): update tools description paragraph and place bulk buttons on a separate row

* fix(mcp): enforce excludeTools in proxy path and align direct-tool counts

- Filter the per-agent tool registry by excludeTools at build time (DB cache
  and lazy-connect paths), so excluded tools are unreachable through the mcp
  proxy (call, search, list, describe) — matching pi-mcp-adapter where
  isToolAllowed gates both direct and gateway exposure.
- Add shared isDirectTool predicate (matches original or prefixed name) used
  by both buildDirectTools and the proxy description counts, so the
  advertised direct/proxy counts can no longer drift from actual
  registration; toolCount now reflects allowed tools only.
- Remove the legacy boolean directTools branch (no legacy data exists).
- Drop the now-unused mcp_excluded_tools_hint i18n key and regenerate
  Paraglide messages.
- Extend unit tests: excluded tools are not counted, listed, searched, or
  callable via the proxy; prefixed-name directTools configs count correctly.
This commit is contained in:
Yiling-J
2026-08-11 15:43:27 +08:00
committed by GitHub
parent 82aee9a291
commit 851ae49c84
33 changed files with 661 additions and 587 deletions
+22 -35
View File
@@ -1,16 +1,18 @@
/**
* Direct MCP tools — per-server opt-in registration.
*
* When a server's config sets `directTools: true`, its allowed tools (after
* excludeTools filters) are registered as native AgentTools with prefixed
* names `{server}_{tool}`. The `mcp` proxy tool stays registered for
* discovery/auth/status and for servers not in direct mode.
* When a server's config sets `directTools` to an array of tool names, its
* allowed tools (matching the original or `{server}_{tool}` prefixed name,
* after excludeTools filters) are registered as native AgentTools with
* prefixed names `{server}_{tool}`. The `mcp` proxy tool stays registered for
* discovery/auth/status and for tools not in direct mode.
*/
import { Type } from '@sinclair/typebox'
import type { AgentTool, AgentToolResult } from '@earendil-works/pi-agent-core'
import '@shumai/db/src/prisma-json-types'
import type { ToolMetadata } from './mcp-tool-registry'
import { isToolAllowed } from './mcp-tool-registry'
import { toToolParameters } from './mcp-tool-schema'
export interface DirectToolCallOptions {
@@ -26,37 +28,19 @@ export interface DirectToolCallOptions {
}>
}
function globToRegExp(pattern: string): RegExp {
const escaped = pattern
.replace(/[.+^${}()|[\]\\]/g, '\\$&')
.replace(/\*/g, '.*')
.replace(/\?/g, '.')
return new RegExp(`^${escaped}$`)
}
function matchesToolPattern(name: string, patterns?: string[]): boolean {
if (!Array.isArray(patterns) || patterns.length === 0) return false
for (const pattern of patterns) {
if (!pattern) continue
if (!pattern.includes('*') && !pattern.includes('?') && name === pattern) return true
if ((pattern.includes('*') || pattern.includes('?')) && globToRegExp(pattern).test(name)) {
return true
}
}
return false
}
/** Decide whether a tool is allowed by excludeTools (matches prefixed or original name). */
export function isToolAllowed(
prefixedName: string,
/**
* Decide whether a tool is exposed as a native direct tool. Matches the
* original MCP name or the `{server}_{tool}` prefixed name against the
* configured directTools array. Shared by direct registration and the proxy
* description counts so the two can never drift apart.
*/
export function isDirectTool(
originalName: string,
config?: PrismaJson.McpServerConfig,
prefixedName: string,
directTools?: string[],
): boolean {
const exclude = config?.excludeTools
if (matchesToolPattern(prefixedName, exclude) || matchesToolPattern(originalName, exclude)) {
return false
}
return true
if (!Array.isArray(directTools)) return false
return directTools.includes(originalName) || directTools.includes(prefixedName)
}
/**
@@ -68,11 +52,14 @@ export function buildDirectTools(
config: PrismaJson.McpServerConfig | undefined,
opts: DirectToolCallOptions,
): AgentTool[] {
if (config?.directTools !== true) return []
const directTools = config?.directTools
if (!Array.isArray(directTools) || directTools.length === 0) return []
const tools: AgentTool[] = []
for (const tool of metadata) {
if (!isToolAllowed(tool.name, tool.originalName, config)) continue
if (!isToolAllowed(tool.name, tool.originalName, config?.excludeTools)) continue
if (!isDirectTool(tool.originalName, tool.name, directTools)) continue
const parameters = toToolParameters(tool.inputSchema)
tools.push({
name: tool.name,
+25 -1
View File
@@ -34,6 +34,7 @@ export interface ProxyServerInfo {
id: string
name: string
toolCount: number
directToolCount?: number
status: string
/** Self-reported server usage instructions (empty when the server provides none). */
instructions?: string
@@ -239,13 +240,36 @@ function notFoundResult(
export function buildProxyDescription(servers: ProxyServerInfo[]): string {
const lines: string[] = []
lines.push('Call MCP (Model Context Protocol) tools exposed by the configured servers.')
const directSummaries: string[] = []
for (const s of servers) {
const directCount = s.directToolCount ?? 0
if (directCount > 0) {
directSummaries.push(`${s.name} (${directCount})`)
}
}
if (directSummaries.length > 0) {
lines.push('')
lines.push(`Direct tools available (call as normal tools): ${directSummaries.join(', ')}`)
}
lines.push('')
lines.push('Servers:')
if (servers.length === 0) {
lines.push(' (none assigned)')
} else {
let listedServerCount = 0
for (const s of servers) {
lines.push(` - ${s.name} (${s.toolCount} tools, status: ${s.status})`)
const directCount = s.directToolCount ?? 0
const proxyCount = Math.max(0, s.toolCount - directCount)
if (proxyCount > 0 || directCount === 0) {
lines.push(` - ${s.name} (${proxyCount} tools, status: ${s.status})`)
listedServerCount++
}
}
if (listedServerCount === 0) {
lines.push(' (all assigned tools are configured as direct tools)')
}
}
lines.push('')
+59 -7
View File
@@ -683,11 +683,11 @@ describe('McpService', () => {
try {
const assigned = await service.createServer(teamId, {
url: assignedSrv.url,
config: { directTools: true },
config: { directTools: ['tavily_search'] },
})
const unassigned = await service.createServer(teamId, {
url: unassignedSrv.url,
config: { directTools: true },
config: { directTools: ['search_records'] },
})
await service.refreshServer(assigned.id)
await service.refreshServer(unassigned.id)
@@ -711,17 +711,25 @@ describe('McpService', () => {
const agent = await seedAgentAndUser(teamId, 'Direct Agent')
const server = await service.createServer(teamId, {
url: srv.url,
config: { directTools: true },
config: { directTools: ['echo', 'add'] },
})
await service.refreshServer(server.id)
await prisma.agentMcpServer.create({ data: { agentId: agent.id, mcpServerId: server.id } })
const tools = await service.buildAgentTools(agent.id, teamId)
expect(tools.length).toBe(4) // proxy + 3 direct tools
expect(tools.length).toBe(3) // proxy + 2 direct tools ('echo', 'add')
const names = tools.map((t) => t.name)
expect(names).toContain('mcp')
expect(names).toContain('test_mcp_server_echo')
expect(names).toContain('test_mcp_server_add')
expect(names).not.toContain('test_mcp_server_list_sims') // kept as proxy tool only
// Dynamic proxy description shows direct summary and remaining proxy count.
const proxy = tools.find((t) => t.name === 'mcp')!
expect(proxy.description).toContain(
'Direct tools available (call as normal tools): test-mcp-server (2)',
)
expect(proxy.description).toContain('test-mcp-server (1 tools, status:')
// Direct tool executes through callMcpTool.
const echo = tools.find((t) => t.name === 'test_mcp_server_echo')!
@@ -734,11 +742,11 @@ describe('McpService', () => {
expect(JSON.stringify(result.content)).toContain('echo:direct')
})
it('applies excludeTools filters to direct tools', async () => {
it('applies excludeTools filters to direct tools and the proxy', async () => {
const agent = await seedAgentAndUser(teamId, 'Filtered Agent')
const server = await service.createServer(teamId, {
url: srv.url,
config: { directTools: true, excludeTools: ['add'] },
config: { directTools: ['echo', 'add'], excludeTools: ['add'] },
})
await service.refreshServer(server.id)
await prisma.agentMcpServer.create({ data: { agentId: agent.id, mcpServerId: server.id } })
@@ -746,8 +754,52 @@ describe('McpService', () => {
const tools = await service.buildAgentTools(agent.id, teamId)
const names = tools.map((t) => t.name)
expect(names).toContain('test_mcp_server_echo')
expect(names).toContain('test_mcp_server_list_sims')
expect(names).not.toContain('test_mcp_server_add')
// The excluded tool is also unreachable through the proxy: it is not
// counted, listed, searched, or callable.
const proxy = tools.find((t) => t.name === 'mcp')!
expect(proxy.description).toContain(
'Direct tools available (call as normal tools): test-mcp-server (1)',
)
expect(proxy.description).toContain('test-mcp-server (1 tools, status:')
const list = await (proxy.execute as ProxyExecute)('excl-list-1', {
server: 'test-mcp-server',
})
expect(JSON.stringify(list.content)).not.toContain('test_mcp_server_add')
const search = await (proxy.execute as ProxyExecute)('excl-search-1', { search: 'add' })
expect(JSON.stringify(search.content)).not.toContain('test_mcp_server_add')
const call = await (proxy.execute as ProxyExecute)('excl-call-1', {
server: 'test-mcp-server',
tool: 'add',
args: { a: 1, b: 2 },
})
expect(JSON.stringify(call.content)).toContain('not found')
})
it('matches directTools by prefixed name in the proxy description counts', async () => {
const agent = await seedAgentAndUser(teamId, 'Prefixed Direct Agent')
const server = await service.createServer(teamId, {
url: srv.url,
config: { directTools: ['test_mcp_server_echo'] },
})
await service.refreshServer(server.id)
await prisma.agentMcpServer.create({ data: { agentId: agent.id, mcpServerId: server.id } })
const tools = await service.buildAgentTools(agent.id, teamId)
const names = tools.map((t) => t.name)
expect(names).toContain('test_mcp_server_echo')
expect(names).not.toContain('test_mcp_server_add')
expect(names).not.toContain('test_mcp_server_list_sims')
const proxy = tools.find((t) => t.name === 'mcp')!
expect(proxy.description).toContain(
'Direct tools available (call as normal tools): test-mcp-server (1)',
)
expect(proxy.description).toContain('test-mcp-server (2 tools, status:')
})
// --------------------------------------------------------------------------
+18 -5
View File
@@ -14,7 +14,7 @@ import type {
} from '@shumai/dtos'
import { logger } from '@shumai/core/src/logger'
import { mcpDbStore, type PendingAuth } from './mcp-db-store'
import { buildDirectTools } from './mcp-direct-tools'
import { buildDirectTools, isDirectTool } from './mcp-direct-tools'
import { McpOauthProvider, type McpOauthConfig } from './mcp-oauth-provider'
import { buildProxyTool, transformMcpContent, type McpProxyToolContext } from './mcp-proxy-tool'
import {
@@ -427,7 +427,9 @@ export class McpService {
const tools = this.toStoredTools(connection.tools)
const metadata = this.serverMetadata(server, connection)
const displayName = metadata.name ?? server.name
registry?.setTools(serverId, displayName, connection.tools)
registry?.setTools(serverId, displayName, connection.tools, {
excludeTools: server.config?.excludeTools,
})
await this.updateStatus(serverId, 'connected', null, {
tools,
lastConnectedAt: new Date(),
@@ -816,6 +818,7 @@ export class McpService {
description: t.description ?? '',
...(t.inputSchema !== undefined ? { inputSchema: t.inputSchema } : {}),
})),
{ excludeTools: s.config?.excludeTools },
)
}
return {
@@ -826,7 +829,6 @@ export class McpService {
transport: s.transport,
authConfig: (s.authConfig ?? {}) as PrismaJson.McpServerAuthConfig,
config: (s.config ?? {}) as PrismaJson.McpServerConfig,
tools: storedTools,
status: s.status,
}
})
@@ -836,10 +838,19 @@ export class McpService {
const proxyServers = servers.map((s) => {
serverNameById.set(s.id, s.name)
serverIdByName.set(s.name, s.id)
// Count direct tools from the same filtered registry metadata that
// buildDirectTools consumes, so the proxy description can never drift
// from what is actually registered as native tools.
const metadata = registry.getTools(s.id)
const directToolCount = metadata.filter((t) =>
isDirectTool(t.originalName, t.name, s.config?.directTools),
).length
return {
id: s.id,
name: s.name,
toolCount: s.tools.length,
toolCount: metadata.length,
directToolCount,
status: s.status,
...(s.instructions !== null && s.instructions !== undefined
? { instructions: s.instructions }
@@ -878,7 +889,9 @@ export class McpService {
const tools: AgentTool[] = [buildProxyTool(ctx)]
for (const server of servers) {
if (server.config?.directTools !== true) continue
if (!Array.isArray(server.config?.directTools) || server.config.directTools.length === 0) {
continue
}
const metadata: ToolMetadata[] = registry.getTools(server.id)
tools.push(
...buildDirectTools(metadata, server.config, {
+60 -8
View File
@@ -35,6 +35,45 @@ export function formatToolName(serverName: string, toolName: string): string {
return serverPart ? `${serverPart}_${sanitized}` : sanitized
}
function globToRegExp(pattern: string): RegExp {
const escaped = pattern
.replace(/[.+^${}()|[\]\\]/g, '\\$&')
.replace(/\*/g, '.*')
.replace(/\?/g, '.')
return new RegExp(`^${escaped}$`)
}
function matchesToolPattern(name: string, patterns?: string[]): boolean {
if (!Array.isArray(patterns) || patterns.length === 0) return false
for (const pattern of patterns) {
if (!pattern) continue
if (!pattern.includes('*') && !pattern.includes('?') && name === pattern) return true
if ((pattern.includes('*') || pattern.includes('?')) && globToRegExp(pattern).test(name)) {
return true
}
}
return false
}
/**
* Decide whether a tool is allowed by excludeTools (matches prefixed or
* original name). Applied when building the per-agent registry so excluded
* tools are invisible to both the proxy tool and direct registration.
*/
export function isToolAllowed(
prefixedName: string,
originalName: string,
excludeTools?: string[],
): boolean {
if (
matchesToolPattern(prefixedName, excludeTools) ||
matchesToolPattern(originalName, excludeTools)
) {
return false
}
return true
}
const MIN_STEM_LENGTH = 4
const FIELD_WEIGHTS = {
@@ -147,14 +186,27 @@ export function paginate<T>(
export class McpToolRegistry {
private readonly metadataByServer = new Map<string, ToolMetadata[]>()
/** Rebuild the metadata for one server from its discovered tools. */
setTools(serverId: string, serverName: string, tools: McpTool[]): void {
const metadata: ToolMetadata[] = tools.map((tool) => ({
name: formatToolName(serverName, tool.name),
originalName: tool.name,
description: tool.description ?? '',
...(tool.inputSchema !== undefined ? { inputSchema: tool.inputSchema } : {}),
}))
/**
* Rebuild the metadata for one server from its discovered tools, skipping
* tools excluded via excludeTools so they are unreachable through the proxy.
*/
setTools(
serverId: string,
serverName: string,
tools: McpTool[],
opts?: { excludeTools?: string[] },
): void {
const metadata: ToolMetadata[] = []
for (const tool of tools) {
const name = formatToolName(serverName, tool.name)
if (!isToolAllowed(name, tool.name, opts?.excludeTools)) continue
metadata.push({
name,
originalName: tool.name,
description: tool.description ?? '',
...(tool.inputSchema !== undefined ? { inputSchema: tool.inputSchema } : {}),
})
}
metadata.sort((a, b) => a.name.localeCompare(b.name))
this.metadataByServer.set(serverId, metadata)
}