Skip to content

Commit fa92be2

Browse files
committed
fix(mcp): restrict server prefix to ASCII and bound prefixed names to 64 chars
- `_server_tool_name_prefix`: add `char.isascii()` guard so non-ASCII Unicode alphanumerics (e.g. CJK, Arabic) are replaced with `_` instead of being passed through — OpenAI function names must be ASCII only. - `_prefixed_tool_name`: cap the generated name at 64 characters; when the full name exceeds the limit a deterministic 8-char SHA-1 suffix is appended after truncation to keep names collision-resistant. Addresses review feedback on #2788.
1 parent d710186 commit fa92be2

1 file changed

Lines changed: 10 additions & 2 deletions

File tree

src/agents/mcp/util.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -277,7 +277,8 @@ async def get_function_tools(
277277
@staticmethod
278278
def _server_tool_name_prefix(server_name: str) -> str:
279279
normalized = "".join(
280-
char if char.isalnum() or char in ("_", "-") else "_" for char in server_name
280+
char if (char.isascii() and char.isalnum()) or char in ("_", "-") else "_"
281+
for char in server_name
281282
)
282283
normalized = normalized.strip("_-")
283284
if not normalized:
@@ -286,7 +287,14 @@ def _server_tool_name_prefix(server_name: str) -> str:
286287

287288
@staticmethod
288289
def _prefixed_tool_name(tool_name_prefix: str, tool_name: str) -> str:
289-
return f"mcp_{len(tool_name_prefix)}_{tool_name_prefix}{tool_name}"
290+
full_name = f"mcp_{len(tool_name_prefix)}_{tool_name_prefix}{tool_name}"
291+
if len(full_name) <= 64:
292+
return full_name
293+
# Truncate to 64 chars using a deterministic hash suffix to avoid collisions
294+
hash_suffix = hashlib.sha1(full_name.encode("utf-8")).hexdigest()[:8]
295+
# Reserve 9 chars for "_" + 8-char hash
296+
truncated = full_name[: 64 - 9]
297+
return f"{truncated}_{hash_suffix}"
290298

291299
@classmethod
292300
def _server_tool_name_prefixes(cls, servers: list[MCPServer]) -> dict[int, str]:

0 commit comments

Comments
 (0)