example-remote-client/src/utils/mcpUtils.ts
Jerome 0266b4871e
Fix server name normalization for tool routing compatibility
## Problem
MCP server names with invalid characters (spaces, special chars, etc.)
caused tool routing failures when prefixed to tool names, as OpenRouter
API requires tool names to match pattern ^[a-zA-Z0-9_-]{1,64}$

## Solution
- **Added normalizeServerName utility**: Converts invalid characters to underscores
- **Centralized normalization logic**: Shared utility prevents code duplication
- **Fixed tool routing**: Agent loop now matches normalized server names correctly
- **Updated tool discovery**: MCP tools use normalized prefixes consistently

## Examples
- "My Weather Service\!" → "My_Weather_Service"
- "Test@Server#123" → "Test_Server_123"
- "Server...with...dots" → "Server_with_dots"
- "  spaces_and__double__underscores  " → "spaces_and_double_underscores"

## Technical Details
- Created /src/utils/mcpUtils.ts for shared normalization function
- Updated MCPConnectionManager to use normalized prefixes in tool names
- Fixed agent loop to match connections using normalized names
- Maintains original server names in UI while using normalized names for API

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-06-12 14:23:51 +01:00

14 lines
No EOL
650 B
TypeScript

// Utility functions for MCP server name normalization
/**
* Normalize server name to comply with OpenRouter API tool naming requirements
* Pattern: ^[a-zA-Z0-9_-]{1,64}$
*/
export function normalizeServerName(name: string): string {
return name
.replace(/[^a-zA-Z0-9_-]/g, '_') // Replace invalid characters with underscore
.replace(/_{2,}/g, '_') // Replace multiple underscores with single
.replace(/^_+|_+$/g, '') // Remove leading/trailing underscores
.substring(0, 32) // Limit length to leave room for tool name
|| 'server'; // Fallback if name becomes empty
}