MCP Server Name Validation in Dify Plugin Tools: Regex Pattern Explained

The junjiem/dify-plugin-tools-mcp_sse repository enforces strict MCP server name validation using the regex pattern ^[a-zA-Z0-9_-]+$ in utils/mcp_client.py to prevent injection attacks and ensure safe configuration key usage.

When configuring MCP (Model Context Protocol) servers within the Dify plugin ecosystem, the system validates every server name against a strict alphanumeric pattern. This validation occurs in the McpClients class within the junjiem/dify-plugin-tools-mcp_sse repository, ensuring that only safe, identifier-style strings are used as configuration keys throughout the application lifecycle.

Where MCP Server Name Validation Occurs

The validation logic resides in the init_client static method of the McpClients class inside utils/mcp_client.py. When instantiating a new MCP client, the method checks the server name before establishing any connection:

if not re.fullmatch(r'^[a-zA-Z0-9_-]+$', name):
    raise Exception(
        f"Invalid server name '{name}': string does not match pattern. "
        f"Expected a string that matches the pattern '^[a-zA-Z0-9_-]+$'."
    )

This early validation ensures that invalid server names trigger immediate exceptions with clear error messages, preventing downstream failures in network requests or configuration parsing.

Breaking Down the Regex Pattern ^[a-zA-Z0-9_-]+$

The regex pattern ^[a-zA-Z0-9_-]+$ enforces four specific constraints on MCP server names:

Anchor Constraints (^ and $)

The caret (^) and dollar sign ($) anchors ensure that the entire string must match the pattern, not just a substring. This prevents partial matches where invalid characters might exist at the beginning or end of the server name.

Allowed Character Classes

The character class [a-zA-Z0-9_-] restricts input to ASCII alphanumeric characters (both uppercase and lowercase), hyphens (-), and underscores (_). This explicitly excludes:

  • Spaces and tabs
  • Forward slashes (/) and backslashes (\)
  • Punctuation marks (., !, ?, :, etc.)
  • Unicode characters and emojis
  • Control characters

Quantifier Requirements (+)

The plus sign (+) quantifier requires at least one character to be present, preventing empty strings from being accepted as valid server names.

Why Strict MCP Server Name Validation Matters

The restrictive regex pattern serves four critical security and operational purposes within the Dify plugin architecture:

Configuration Key Consistency

Server names become dictionary keys in the servers_config mapping. Restricting names to simple identifiers prevents key collisions and ensures that configuration lookups remain predictable across the application lifecycle.

Injection Attack Prevention

By disallowing characters like /, \, ", ', :, and ;, the validation blocks malicious payloads that could be interpreted as path traversal sequences, JSON injection attempts, or shell metacharacters when server names are embedded in HTTP headers, log messages, or command arguments.

URL Construction Safety

Some MCP transport implementations embed server names in request paths or query parameters. The alphanumeric restriction guarantees that constructed URLs remain well-formed and properly encoded, preventing broken endpoints or unexpected routing behavior.

Early Error Detection

Raising an explicit exception during client initialization makes misconfigurations immediately obvious to developers and administrators, rather than allowing invalid names to propagate and cause obscure network errors or authentication failures later in the execution flow.

Valid and Invalid Server Name Examples

Valid Server Names

The following code demonstrates successful validation of compliant server names:

from utils.mcp_client import McpClients

servers_cfg = {
    "my_server-01": {"url": "https://example.com/mcp", "transport": "sse"},
    "productionAPI": {"url": "https://api.example.com/mcp"},
    "mcp-server_v2": {"url": "https://mcp.example.com/sse"}
}

clients = McpClients(servers_cfg)  # ✅ No exception raised

print(clients._clients.keys())     # Output: dict_keys(['my_server-01', 'productionAPI', 'mcp-server_v2'])

Invalid Server Names

Attempting to use non-compliant names triggers immediate validation errors:

from utils.mcp_client import McpClients

servers_cfg = {
    "bad server!": {"url": "https://example.com/mcp"},  # Contains space and '!'

    "config/path": {"url": "https://example.com/mcp"},  # Contains forward slash

    "": {"url": "https://example.com/mcp"}               # Empty string

}

try:
    McpClients(servers_cfg)
except Exception as e:
    print(e)
    # Output: Invalid server name 'bad server!': string does not match pattern. 

    # Expected a string that matches the pattern '^[a-zA-Z0-9_-]+$'.

Summary

  • Validation Location: The McpClients.init_client method in utils/mcp_client.py enforces server name constraints using re.fullmatch.
  • Regex Pattern: The pattern ^[a-zA-Z0-9_-]+$ restricts names to alphanumeric characters, hyphens, and underscores only.
  • Security Purpose: The validation prevents injection attacks by blocking path separators, quotes, and special characters that could compromise URL construction or configuration parsing.
  • Operational Benefit: Early validation ensures server names function reliably as dictionary keys and prevents obscure runtime errors in MCP transport layers.

Frequently Asked Questions

Why does the MCP server name validation reject spaces and punctuation?

Spaces and punctuation marks are rejected because they create ambiguity in configuration parsing and URL construction. Characters like spaces require URL encoding, while punctuation such as quotes or colons could break JSON serialization or enable injection attacks when server names are embedded in HTTP headers or log messages.

Can I use Unicode characters or emojis in MCP server names?

No, the regex pattern ^[a-zA-Z0-9_-]+$ explicitly limits input to ASCII alphanumeric characters, hyphens, and underscores. Unicode characters, including emojis and non-Latin scripts, are not permitted. This restriction ensures compatibility across different transport protocols and prevents encoding issues in configuration files.

What happens if I provide an empty string as a server name?

An empty string will fail validation because the regex pattern requires at least one character (the + quantifier). The McpClients constructor will raise an exception immediately with the message indicating that the string does not match the expected pattern, preventing the creation of invalid configuration entries.

Where can I modify the server name validation rules?

The validation logic is hardcoded in the init_client static method within utils/mcp_client.py at lines 44-48. To modify the allowed character set, you would need to edit the regex pattern ^[a-zA-Z0-9_-]+$ in this file. However, changing this pattern is not recommended, as it could introduce security vulnerabilities or break compatibility with the Dify plugin's configuration handling.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →