MCP authentication parameter implementation

This commit is contained in:
Omar Abdelwahab 2025-11-03 15:48:56 -08:00
parent da57b51fb6
commit d0a8878337
7 changed files with 375 additions and 2 deletions

View file

@ -479,6 +479,26 @@ class AllowedToolsFilter(BaseModel):
tool_names: list[str] | None = None
@json_schema_type
class MCPAuthentication(BaseModel):
"""Authentication configuration for MCP servers.
:param type: Authentication type ("bearer", "basic", or "api_key")
:param token: Bearer token for bearer authentication
:param username: Username for basic authentication
:param password: Password for basic authentication
:param api_key: API key for api_key authentication
:param header_name: Custom header name for API key (default: "X-API-Key")
"""
type: Literal["bearer", "basic", "api_key"]
token: str | None = None
username: str | None = None
password: str | None = None
api_key: str | None = None
header_name: str = "X-API-Key"
@json_schema_type
class OpenAIResponseInputToolMCP(BaseModel):
"""Model Context Protocol (MCP) tool configuration for OpenAI response inputs.
@ -487,6 +507,7 @@ class OpenAIResponseInputToolMCP(BaseModel):
:param server_label: Label to identify this MCP server
:param server_url: URL endpoint of the MCP server
:param headers: (Optional) HTTP headers to include when connecting to the server
:param authentication: (Optional) Authentication configuration for the MCP server
:param require_approval: Approval requirement for tool calls ("always", "never", or filter)
:param allowed_tools: (Optional) Restriction on which tools can be used from this server
"""
@ -495,6 +516,7 @@ class OpenAIResponseInputToolMCP(BaseModel):
server_label: str
server_url: str
headers: dict[str, Any] | None = None
authentication: MCPAuthentication | None = None
require_approval: Literal["always"] | Literal["never"] | ApprovalFilter = "never"
allowed_tools: list[str] | AllowedToolsFilter | None = None

View file

@ -11,6 +11,7 @@ from typing import Any
from llama_stack.apis.agents.openai_responses import (
AllowedToolsFilter,
ApprovalFilter,
MCPAuthentication,
MCPListToolsTool,
OpenAIResponseContentPartOutputText,
OpenAIResponseContentPartReasoningText,
@ -80,6 +81,34 @@ from .utils import (
logger = get_logger(name=__name__, category="agents::meta_reference")
def _convert_authentication_to_headers(auth: MCPAuthentication) -> dict[str, str]:
"""Convert MCPAuthentication config to HTTP headers.
Args:
auth: Authentication configuration
Returns:
Dictionary of HTTP headers for authentication
"""
headers = {}
if auth.type == "bearer":
if auth.token:
headers["Authorization"] = f"Bearer {auth.token}"
elif auth.type == "basic":
if auth.username and auth.password:
import base64
credentials = f"{auth.username}:{auth.password}"
encoded = base64.b64encode(credentials.encode()).decode()
headers["Authorization"] = f"Basic {encoded}"
elif auth.type == "api_key":
if auth.api_key:
headers[auth.header_name] = auth.api_key
return headers
def convert_tooldef_to_chat_tool(tool_def):
"""Convert a ToolDef to OpenAI ChatCompletionToolParam format.
@ -1079,10 +1108,20 @@ class StreamingResponseOrchestrator:
"server_url": mcp_tool.server_url,
"mcp_list_tools_id": list_id,
}
# Prepare headers with authentication from tool config
headers = dict(mcp_tool.headers or {})
if mcp_tool.authentication:
auth_headers = _convert_authentication_to_headers(mcp_tool.authentication)
# Don't override existing headers (case-insensitive check)
existing_keys_lower = {k.lower() for k in headers.keys()}
for key, value in auth_headers.items():
if key.lower() not in existing_keys_lower:
headers[key] = value
async with tracing.span("list_mcp_tools", attributes):
tool_defs = await list_mcp_tools(
endpoint=mcp_tool.server_url,
headers=mcp_tool.headers or {},
headers=headers,
)
# Create the MCP list tools message

View file

@ -10,6 +10,7 @@ from collections.abc import AsyncIterator
from typing import Any
from llama_stack.apis.agents.openai_responses import (
MCPAuthentication,
OpenAIResponseInputToolFileSearch,
OpenAIResponseInputToolMCP,
OpenAIResponseObjectStreamResponseFileSearchCallCompleted,
@ -47,6 +48,34 @@ from .types import ChatCompletionContext, ToolExecutionResult
logger = get_logger(name=__name__, category="agents::meta_reference")
def _convert_authentication_to_headers(auth: MCPAuthentication) -> dict[str, str]:
"""Convert MCPAuthentication config to HTTP headers.
Args:
auth: Authentication configuration
Returns:
Dictionary of HTTP headers for authentication
"""
headers = {}
if auth.type == "bearer":
if auth.token:
headers["Authorization"] = f"Bearer {auth.token}"
elif auth.type == "basic":
if auth.username and auth.password:
import base64
credentials = f"{auth.username}:{auth.password}"
encoded = base64.b64encode(credentials.encode()).decode()
headers["Authorization"] = f"Basic {encoded}"
elif auth.type == "api_key":
if auth.api_key:
headers[auth.header_name] = auth.api_key
return headers
class ToolExecutor:
def __init__(
self,
@ -299,10 +328,20 @@ class ToolExecutor:
"server_url": mcp_tool.server_url,
"tool_name": function_name,
}
# Prepare headers with authentication from tool config
headers = dict(mcp_tool.headers or {})
if mcp_tool.authentication:
auth_headers = _convert_authentication_to_headers(mcp_tool.authentication)
# Don't override existing headers (case-insensitive check)
existing_keys_lower = {k.lower() for k in headers.keys()}
for key, value in auth_headers.items():
if key.lower() not in existing_keys_lower:
headers[key] = value
async with tracing.span("invoke_mcp_tool", attributes):
result = await invoke_mcp_tool(
endpoint=mcp_tool.server_url,
headers=mcp_tool.headers or {},
headers=headers,
tool_name=function_name,
kwargs=tool_kwargs,
)