sample_id
stringlengths
21
196
text
stringlengths
105
936k
metadata
dict
category
stringclasses
6 values
modelcontextprotocol/python-sdk:tests/experimental/tasks/test_message_queue.py
"""Tests for TaskMessageQueue and InMemoryTaskMessageQueue.""" from collections import deque from datetime import datetime, timezone import anyio import pytest from mcp.shared.experimental.tasks.message_queue import InMemoryTaskMessageQueue, QueuedMessage from mcp.shared.experimental.tasks.resolver import Resolver f...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "tests/experimental/tasks/test_message_queue.py", "license": "MIT License", "lines": 250, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
modelcontextprotocol/python-sdk:tests/experimental/tasks/test_request_context.py
"""Tests for the RequestContext.experimental (Experimental class) task validation helpers.""" import pytest from mcp.server.experimental.request_context import Experimental from mcp.shared.exceptions import MCPError from mcp.types import ( METHOD_NOT_FOUND, TASK_FORBIDDEN, TASK_OPTIONAL, TASK_REQUIRED...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "tests/experimental/tasks/test_request_context.py", "license": "MIT License", "lines": 120, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
modelcontextprotocol/python-sdk:tests/experimental/tasks/test_spec_compliance.py
"""Tasks Spec Compliance Tests =========================== Test structure mirrors: https://modelcontextprotocol.io/specification/draft/basic/utilities/tasks.md Each section contains tests for normative requirements (MUST/SHOULD/MAY). """ from datetime import datetime, timezone import pytest from mcp.server import ...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "tests/experimental/tasks/test_spec_compliance.py", "license": "MIT License", "lines": 541, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
modelcontextprotocol/python-sdk:tests/server/test_validation.py
"""Tests for server validation functions.""" import pytest from mcp.server.validation import ( check_sampling_tools_capability, validate_sampling_tools, validate_tool_use_result_messages, ) from mcp.shared.exceptions import MCPError from mcp.types import ( ClientCapabilities, SamplingCapability, ...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "tests/server/test_validation.py", "license": "MIT License", "lines": 116, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
modelcontextprotocol/python-sdk:examples/snippets/clients/url_elicitation_client.py
"""URL Elicitation Client Example. Demonstrates how clients handle URL elicitation requests from servers. This is the Python equivalent of TypeScript SDK's elicitationUrlExample.ts, focused on URL elicitation patterns without OAuth complexity. Features demonstrated: 1. Client elicitation capability declaration 2. Han...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/snippets/clients/url_elicitation_client.py", "license": "MIT License", "lines": 253, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
modelcontextprotocol/python-sdk:tests/shared/test_exceptions.py
"""Tests for MCP exception classes.""" import pytest from mcp.shared.exceptions import MCPError, UrlElicitationRequiredError from mcp.types import URL_ELICITATION_REQUIRED, ElicitRequestURLParams, ErrorData def test_url_elicitation_required_error_create_with_single_elicitation() -> None: """Test creating error ...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "tests/shared/test_exceptions.py", "license": "MIT License", "lines": 132, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
modelcontextprotocol/python-sdk:src/mcp/shared/tool_name_validation.py
"""Tool name validation utilities according to SEP-986. Tool names SHOULD be between 1 and 128 characters in length (inclusive). Tool names are case-sensitive. Allowed characters: uppercase and lowercase ASCII letters (A-Z, a-z), digits (0-9), underscore (_), dash (-), and dot (.). Tool names SHOULD NOT contain spaces...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "src/mcp/shared/tool_name_validation.py", "license": "MIT License", "lines": 95, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
modelcontextprotocol/python-sdk:tests/shared/test_tool_name_validation.py
"""Tests for tool name validation utilities (SEP-986).""" import logging import pytest from mcp.shared.tool_name_validation import ( issue_tool_name_warning, validate_and_warn_tool_name, validate_tool_name, ) # Tests for validate_tool_name function - valid names @pytest.mark.parametrize( "tool_nam...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "tests/shared/test_tool_name_validation.py", "license": "MIT License", "lines": 156, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
modelcontextprotocol/python-sdk:tests/client/test_scope_bug_1630.py
"""Regression test for issue #1630: OAuth2 scope incorrectly set to resource_metadata URL. This test verifies that when a 401 response contains both resource_metadata and scope in the WWW-Authenticate header, the actual scope is used (not the resource_metadata URL). """ from unittest import mock import httpx import ...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "tests/client/test_scope_bug_1630.py", "license": "MIT License", "lines": 127, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
modelcontextprotocol/python-sdk:src/mcp/client/auth/exceptions.py
class OAuthFlowError(Exception): """Base exception for OAuth flow errors.""" class OAuthTokenError(OAuthFlowError): """Raised when token operations fail.""" class OAuthRegistrationError(OAuthFlowError): """Raised when client registration fails."""
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "src/mcp/client/auth/exceptions.py", "license": "MIT License", "lines": 6, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
modelcontextprotocol/python-sdk:src/mcp/client/auth/utils.py
import re from urllib.parse import urljoin, urlparse from httpx import Request, Response from pydantic import AnyUrl, ValidationError from mcp.client.auth import OAuthRegistrationError, OAuthTokenError from mcp.client.streamable_http import MCP_PROTOCOL_VERSION from mcp.shared.auth import ( OAuthClientInformation...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "src/mcp/client/auth/utils.py", "license": "MIT License", "lines": 248, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
modelcontextprotocol/python-sdk:examples/servers/everything-server/mcp_everything_server/server.py
#!/usr/bin/env python3 """MCP Everything Server - Conformance Test Server Server implementing all MCP features for conformance testing based on Conformance Server Specification. """ import asyncio import base64 import json import logging import click from mcp.server import ServerRequestContext from mcp.server.mcpser...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/servers/everything-server/mcp_everything_server/server.py", "license": "MIT License", "lines": 369, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
modelcontextprotocol/python-sdk:src/mcp/client/auth/extensions/client_credentials.py
"""OAuth client credential extensions for MCP. Provides OAuth providers for machine-to-machine authentication flows: - ClientCredentialsOAuthProvider: For client_credentials with client_id + client_secret - PrivateKeyJWTOAuthProvider: For client_credentials with private_key_jwt authentication (typically using a pre-...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "src/mcp/client/auth/extensions/client_credentials.py", "license": "MIT License", "lines": 398, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
modelcontextprotocol/python-sdk:tests/client/auth/extensions/test_client_credentials.py
import urllib.parse import warnings import jwt import pytest from pydantic import AnyHttpUrl, AnyUrl from mcp.client.auth.extensions.client_credentials import ( ClientCredentialsOAuthProvider, JWTParameters, PrivateKeyJWTOAuthProvider, RFC7523OAuthClientProvider, SignedJWTParameters, static_as...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "tests/client/auth/extensions/test_client_credentials.py", "license": "MIT License", "lines": 415, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
modelcontextprotocol/python-sdk:tests/test_helpers.py
"""Common test utilities for MCP server tests.""" import socket import time def wait_for_server(port: int, timeout: float = 20.0) -> None: """Wait for server to be ready to accept connections. Polls the server port until it accepts connections or timeout is reached. This eliminates race conditions witho...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "tests/test_helpers.py", "license": "MIT License", "lines": 25, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
modelcontextprotocol/python-sdk:examples/snippets/servers/direct_call_tool_result.py
"""Example showing direct CallToolResult return for advanced control.""" from typing import Annotated from pydantic import BaseModel from mcp.server.mcpserver import MCPServer from mcp.types import CallToolResult, TextContent mcp = MCPServer("CallToolResult Example") class ValidationModel(BaseModel): """Model...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/snippets/servers/direct_call_tool_result.py", "license": "MIT License", "lines": 29, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
modelcontextprotocol/python-sdk:examples/snippets/servers/lowlevel/direct_call_tool_result.py
"""Run from the repository root: uv run examples/snippets/servers/lowlevel/direct_call_tool_result.py """ import asyncio import mcp.server.stdio from mcp import types from mcp.server import Server, ServerRequestContext async def handle_list_tools( ctx: ServerRequestContext, params: types.PaginatedRequestParams ...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/snippets/servers/lowlevel/direct_call_tool_result.py", "license": "MIT License", "lines": 49, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
modelcontextprotocol/python-sdk:tests/server/test_session_race_condition.py
"""Test for race condition fix in initialization flow. This test verifies that requests can be processed immediately after responding to InitializeRequest, without waiting for InitializedNotification. This is critical for HTTP transport where requests can arrive in any order. """ import anyio import pytest from mcp...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "tests/server/test_session_race_condition.py", "license": "MIT License", "lines": 111, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
modelcontextprotocol/python-sdk:tests/server/test_lowlevel_exception_handling.py
from unittest.mock import AsyncMock, Mock import pytest from mcp import types from mcp.server.lowlevel.server import Server from mcp.server.session import ServerSession from mcp.shared.session import RequestResponder @pytest.mark.anyio async def test_exception_handling_with_raise_exceptions_true(): """Test that...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "tests/server/test_lowlevel_exception_handling.py", "license": "MIT License", "lines": 55, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
modelcontextprotocol/python-sdk:tests/issues/test_1338_icons_and_metadata.py
"""Test icon and metadata support (SEP-973).""" import pytest from mcp.server.mcpserver import MCPServer from mcp.types import Icon pytestmark = pytest.mark.anyio async def test_icons_and_website_url(): """Test that icons and websiteUrl are properly returned in API calls.""" # Create test icon test_ic...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "tests/issues/test_1338_icons_and_metadata.py", "license": "MIT License", "lines": 114, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
modelcontextprotocol/python-sdk:examples/servers/simple-pagination/mcp_simple_pagination/server.py
"""Simple MCP server demonstrating pagination for tools, resources, and prompts. This example shows how to implement pagination with the low-level server API to handle large lists of items that need to be split across multiple pages. """ from typing import TypeVar import anyio import click from mcp import types from...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/servers/simple-pagination/mcp_simple_pagination/server.py", "license": "MIT License", "lines": 160, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
modelcontextprotocol/python-sdk:examples/snippets/clients/pagination_client.py
"""Example of consuming paginated MCP endpoints from a client.""" import asyncio from mcp.client.session import ClientSession from mcp.client.stdio import StdioServerParameters, stdio_client from mcp.types import PaginatedRequestParams, Resource async def list_all_resources() -> None: """Fetch all resources usi...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/snippets/clients/pagination_client.py", "license": "MIT License", "lines": 28, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
modelcontextprotocol/python-sdk:examples/snippets/servers/pagination_example.py
"""Example of implementing pagination with the low-level MCP server.""" from mcp import types from mcp.server import Server, ServerRequestContext # Sample data to paginate ITEMS = [f"Item {i}" for i in range(1, 101)] # 100 items async def handle_list_resources( ctx: ServerRequestContext, params: types.Paginate...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/snippets/servers/pagination_example.py", "license": "MIT License", "lines": 24, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
modelcontextprotocol/python-sdk:tests/server/lowlevel/test_server_listing.py
"""Basic tests for list_prompts, list_resources, and list_tools handlers without pagination.""" import pytest from mcp import Client from mcp.server import Server, ServerRequestContext from mcp.types import ( ListPromptsResult, ListResourcesResult, ListToolsResult, PaginatedRequestParams, Prompt, ...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "tests/server/lowlevel/test_server_listing.py", "license": "MIT License", "lines": 108, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
modelcontextprotocol/python-sdk:tests/server/lowlevel/test_server_pagination.py
import pytest from mcp import Client from mcp.server import Server, ServerRequestContext from mcp.types import ( ListPromptsResult, ListResourcesResult, ListToolsResult, PaginatedRequestParams, ) @pytest.mark.anyio async def test_list_prompts_pagination() -> None: test_cursor = "test-cursor-123" ...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "tests/server/lowlevel/test_server_pagination.py", "license": "MIT License", "lines": 67, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
modelcontextprotocol/python-sdk:tests/server/auth/test_protected_resource.py
"""Integration tests for MCP Oauth Protected Resource.""" from urllib.parse import urlparse import httpx import pytest from inline_snapshot import snapshot from pydantic import AnyHttpUrl from starlette.applications import Starlette from mcp.server.auth.routes import build_resource_metadata_url, create_protected_res...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "tests/server/auth/test_protected_resource.py", "license": "MIT License", "lines": 151, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
modelcontextprotocol/python-sdk:tests/client/test_notification_response.py
"""Tests for StreamableHTTP client transport with non-SDK servers. These tests verify client behavior when interacting with servers that don't follow SDK conventions. """ import json import httpx import pytest from starlette.applications import Starlette from starlette.requests import Request from starlette.response...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "tests/client/test_notification_response.py", "license": "MIT License", "lines": 144, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
modelcontextprotocol/python-sdk:tests/server/auth/test_provider.py
"""Tests for mcp.server.auth.provider module.""" from mcp.server.auth.provider import construct_redirect_uri def test_construct_redirect_uri_no_existing_params(): """Test construct_redirect_uri with no existing query parameters.""" base_uri = "http://localhost:8000/callback" result = construct_redirect_u...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "tests/server/auth/test_provider.py", "license": "MIT License", "lines": 54, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
modelcontextprotocol/python-sdk:examples/snippets/servers/streamable_http_basic_mounting.py
"""Basic example showing how to mount StreamableHTTP server in Starlette. Run from the repository root: uvicorn examples.snippets.servers.streamable_http_basic_mounting:app --reload """ import contextlib from starlette.applications import Starlette from starlette.routing import Mount from mcp.server.mcpserver i...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/snippets/servers/streamable_http_basic_mounting.py", "license": "MIT License", "lines": 27, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
modelcontextprotocol/python-sdk:examples/snippets/servers/streamable_http_host_mounting.py
"""Example showing how to mount StreamableHTTP server using Host-based routing. Run from the repository root: uvicorn examples.snippets.servers.streamable_http_host_mounting:app --reload """ import contextlib from starlette.applications import Starlette from starlette.routing import Host from mcp.server.mcpserv...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/snippets/servers/streamable_http_host_mounting.py", "license": "MIT License", "lines": 27, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
modelcontextprotocol/python-sdk:examples/snippets/servers/streamable_http_multiple_servers.py
"""Example showing how to mount multiple StreamableHTTP servers with path configuration. Run from the repository root: uvicorn examples.snippets.servers.streamable_http_multiple_servers:app --reload """ import contextlib from starlette.applications import Starlette from starlette.routing import Mount from mcp.s...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/snippets/servers/streamable_http_multiple_servers.py", "license": "MIT License", "lines": 35, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
modelcontextprotocol/python-sdk:examples/snippets/servers/streamable_http_path_config.py
"""Example showing path configuration when mounting MCPServer. Run from the repository root: uvicorn examples.snippets.servers.streamable_http_path_config:app --reload """ from starlette.applications import Starlette from starlette.routing import Mount from mcp.server.mcpserver import MCPServer # Create a simpl...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/snippets/servers/streamable_http_path_config.py", "license": "MIT License", "lines": 23, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
modelcontextprotocol/python-sdk:tests/server/test_cancel_handling.py
"""Test that cancelled requests don't cause double responses.""" import anyio import pytest from mcp import Client from mcp.server import Server, ServerRequestContext from mcp.shared.exceptions import MCPError from mcp.types import ( CallToolRequest, CallToolRequestParams, CallToolResult, CancelledNot...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "tests/server/test_cancel_handling.py", "license": "MIT License", "lines": 78, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
modelcontextprotocol/python-sdk:tests/shared/test_auth.py
"""Tests for OAuth 2.0 shared code.""" from mcp.shared.auth import OAuthMetadata def test_oauth(): """Should not throw when parsing OAuth metadata.""" OAuthMetadata.model_validate( { "issuer": "https://example.com", "authorization_endpoint": "https://example.com/oauth2/authori...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "tests/shared/test_auth.py", "license": "MIT License", "lines": 53, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
modelcontextprotocol/python-sdk:examples/snippets/clients/oauth_client.py
"""Before running, specify running MCP RS server URL. To spin up RS server locally, see examples/servers/simple-auth/README.md cd to the `examples/snippets` directory and run: uv run oauth-client """ import asyncio from urllib.parse import parse_qs, urlparse import httpx from pydantic import AnyUrl from mcp...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/snippets/clients/oauth_client.py", "license": "MIT License", "lines": 64, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
modelcontextprotocol/python-sdk:examples/snippets/servers/oauth_server.py
"""Run from the repository root: uv run examples/snippets/servers/oauth_server.py """ from pydantic import AnyHttpUrl from mcp.server.auth.provider import AccessToken, TokenVerifier from mcp.server.auth.settings import AuthSettings from mcp.server.mcpserver import MCPServer class SimpleTokenVerifier(TokenVerifier):...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/snippets/servers/oauth_server.py", "license": "MIT License", "lines": 34, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
modelcontextprotocol/python-sdk:examples/snippets/clients/parsing_tool_results.py
"""examples/snippets/clients/parsing_tool_results.py""" import asyncio from mcp import ClientSession, StdioServerParameters, types from mcp.client.stdio import stdio_client async def parse_tool_results(): """Demonstrates how to parse different types of content in CallToolResult.""" server_params = StdioServ...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/snippets/clients/parsing_tool_results.py", "license": "MIT License", "lines": 46, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
modelcontextprotocol/python-sdk:tests/cli/test_utils.py
import subprocess import sys from pathlib import Path from typing import Any import pytest from mcp.cli.cli import _build_uv_command, _get_npx_command, _parse_file_path # type: ignore[reportPrivateUsage] @pytest.mark.parametrize( "spec, expected_obj", [ ("server.py", None), ("foo.py:srv_obj...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "tests/cli/test_utils.py", "license": "MIT License", "lines": 79, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
modelcontextprotocol/python-sdk:examples/snippets/clients/streamable_basic.py
"""Run from the repository root: uv run examples/snippets/clients/streamable_basic.py """ import asyncio from mcp import ClientSession from mcp.client.streamable_http import streamable_http_client async def main(): # Connect to a streamable HTTP server async with streamable_http_client("http://localhost:800...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/snippets/clients/streamable_basic.py", "license": "MIT License", "lines": 18, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
modelcontextprotocol/python-sdk:examples/snippets/servers/streamable_config.py
"""Run from the repository root: uv run examples/snippets/servers/streamable_config.py """ from mcp.server.mcpserver import MCPServer mcp = MCPServer("StatelessServer") # Add a simple tool to demonstrate the server @mcp.tool() def greet(name: str = "World") -> str: """Greet someone by name.""" return f"Hell...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/snippets/servers/streamable_config.py", "license": "MIT License", "lines": 20, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
modelcontextprotocol/python-sdk:examples/snippets/servers/streamable_starlette_mount.py
"""Run from the repository root: uvicorn examples.snippets.servers.streamable_starlette_mount:app --reload """ import contextlib from starlette.applications import Starlette from starlette.routing import Mount from mcp.server.mcpserver import MCPServer # Create the Echo server echo_mcp = MCPServer(name="EchoServer"...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/snippets/servers/streamable_starlette_mount.py", "license": "MIT License", "lines": 38, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
modelcontextprotocol/python-sdk:examples/snippets/servers/lowlevel/basic.py
"""Run from the repository root: uv run examples/snippets/servers/lowlevel/basic.py """ import asyncio import mcp.server.stdio from mcp import types from mcp.server import Server, ServerRequestContext async def handle_list_prompts( ctx: ServerRequestContext, params: types.PaginatedRequestParams | None ) -> type...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/snippets/servers/lowlevel/basic.py", "license": "MIT License", "lines": 49, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
modelcontextprotocol/python-sdk:examples/snippets/servers/lowlevel/lifespan.py
"""Run from the repository root: uv run examples/snippets/servers/lowlevel/lifespan.py """ from collections.abc import AsyncIterator from contextlib import asynccontextmanager from typing import TypedDict import mcp.server.stdio from mcp import types from mcp.server import Server, ServerRequestContext # Mock databa...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/snippets/servers/lowlevel/lifespan.py", "license": "MIT License", "lines": 77, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
modelcontextprotocol/python-sdk:examples/snippets/servers/lowlevel/structured_output.py
"""Run from the repository root: uv run examples/snippets/servers/lowlevel/structured_output.py """ import asyncio import json import mcp.server.stdio from mcp import types from mcp.server import Server, ServerRequestContext async def handle_list_tools( ctx: ServerRequestContext, params: types.PaginatedRequestP...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/snippets/servers/lowlevel/structured_output.py", "license": "MIT License", "lines": 65, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
modelcontextprotocol/python-sdk:examples/snippets/clients/display_utilities.py
"""cd to the `examples/snippets` directory and run: uv run display-utilities-client """ import asyncio import os from mcp import ClientSession, StdioServerParameters from mcp.client.stdio import stdio_client from mcp.shared.metadata_utils import get_display_name # Create server parameters for stdio connection server...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/snippets/clients/display_utilities.py", "license": "MIT License", "lines": 48, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
modelcontextprotocol/python-sdk:examples/snippets/servers/direct_execution.py
"""Example showing direct execution of an MCP server. This is the simplest way to run an MCP server directly. cd to the `examples/snippets` directory and run: uv run direct-execution-server or python servers/direct_execution.py """ from mcp.server.mcpserver import MCPServer mcp = MCPServer("My App") @m...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/snippets/servers/direct_execution.py", "license": "MIT License", "lines": 18, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
modelcontextprotocol/python-sdk:examples/snippets/clients/completion_client.py
"""cd to the `examples/snippets` directory and run: uv run completion-client """ import asyncio import os from mcp import ClientSession, StdioServerParameters from mcp.client.stdio import stdio_client from mcp.types import PromptReference, ResourceTemplateReference # Create server parameters for stdio connection ser...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/snippets/clients/completion_client.py", "license": "MIT License", "lines": 61, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
modelcontextprotocol/python-sdk:examples/snippets/clients/stdio_client.py
"""cd to the `examples/snippets/clients` directory and run: uv run client """ import asyncio import os from mcp import ClientSession, StdioServerParameters, types from mcp.client.context import ClientRequestContext from mcp.client.stdio import stdio_client # Create server parameters for stdio connection server_param...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/snippets/clients/stdio_client.py", "license": "MIT License", "lines": 63, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
modelcontextprotocol/python-sdk:examples/snippets/servers/images.py
"""Example showing image handling with MCPServer.""" from PIL import Image as PILImage from mcp.server.mcpserver import Image, MCPServer mcp = MCPServer("Image Example") @mcp.tool() def create_thumbnail(image_path: str) -> Image: """Create a thumbnail from an image""" img = PILImage.open(image_path) im...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/snippets/servers/images.py", "license": "MIT License", "lines": 10, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
modelcontextprotocol/python-sdk:examples/snippets/servers/lifespan_example.py
"""Example showing lifespan support for startup/shutdown with strong typing.""" from collections.abc import AsyncIterator from contextlib import asynccontextmanager from dataclasses import dataclass from mcp.server.mcpserver import Context, MCPServer # Mock database class for example class Database: """Mock dat...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/snippets/servers/lifespan_example.py", "license": "MIT License", "lines": 40, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
modelcontextprotocol/python-sdk:examples/snippets/servers/structured_output.py
"""Example showing structured output with tools.""" from typing import TypedDict from pydantic import BaseModel, Field from mcp.server.mcpserver import MCPServer mcp = MCPServer("Structured Output Example") # Using Pydantic models for rich structured data class WeatherData(BaseModel): """Weather information s...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/snippets/servers/structured_output.py", "license": "MIT License", "lines": 69, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
modelcontextprotocol/python-sdk:tests/issues/test_1027_win_unreachable_cleanup.py
"""Regression test for issue #1027: Ensure cleanup procedures run properly during shutdown Issue #1027 reported that cleanup code after "yield" in lifespan was unreachable when processes were terminated. This has been fixed by implementing the MCP spec-compliant stdio shutdown sequence that closes stdin first, allowin...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "tests/issues/test_1027_win_unreachable_cleanup.py", "license": "MIT License", "lines": 191, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
modelcontextprotocol/python-sdk:tests/shared/test_win32_utils.py
"""Windows-specific test utilities.""" def escape_path_for_python(path: str) -> str: """Escape a file path for use in Python code strings. Converts backslashes to forward slashes which work on all platforms and don't need escaping in Python strings. """ return repr(path.replace("\\", "/"))
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "tests/shared/test_win32_utils.py", "license": "MIT License", "lines": 7, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
modelcontextprotocol/python-sdk:tests/issues/test_552_windows_hang.py
"""Test for issue #552: stdio_client hangs on Windows.""" import sys from textwrap import dedent import anyio import pytest from mcp import ClientSession, StdioServerParameters from mcp.client.stdio import stdio_client @pytest.mark.skipif(sys.platform != "win32", reason="Windows-specific test") # pragma: no cover...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "tests/issues/test_552_windows_hang.py", "license": "MIT License", "lines": 52, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
modelcontextprotocol/python-sdk:src/mcp/os/posix/utilities.py
"""POSIX-specific functionality for stdio client operations.""" import logging import os import signal import anyio from anyio.abc import Process logger = logging.getLogger(__name__) async def terminate_posix_process_tree(process: Process, timeout_seconds: float = 2.0) -> None: """Terminate a process and all i...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "src/mcp/os/posix/utilities.py", "license": "MIT License", "lines": 46, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
modelcontextprotocol/python-sdk:examples/snippets/servers/basic_prompt.py
from mcp.server.mcpserver import MCPServer from mcp.server.mcpserver.prompts import base mcp = MCPServer(name="Prompt Example") @mcp.prompt(title="Code Review") def review_code(code: str) -> str: return f"Please review this code:\n\n{code}" @mcp.prompt(title="Debug Assistant") def debug_error(error: str) -> li...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/snippets/servers/basic_prompt.py", "license": "MIT License", "lines": 13, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
modelcontextprotocol/python-sdk:examples/snippets/servers/basic_resource.py
from mcp.server.mcpserver import MCPServer mcp = MCPServer(name="Resource Example") @mcp.resource("file://documents/{name}") def read_document(name: str) -> str: """Read a document by name.""" # This would normally read from disk return f"Content of {name}" @mcp.resource("config://settings") def get_se...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/snippets/servers/basic_resource.py", "license": "MIT License", "lines": 15, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
modelcontextprotocol/python-sdk:examples/snippets/servers/basic_tool.py
from mcp.server.mcpserver import MCPServer mcp = MCPServer(name="Tool Example") @mcp.tool() def sum(a: int, b: int) -> int: """Add two numbers together.""" return a + b @mcp.tool() def get_weather(city: str, unit: str = "celsius") -> str: """Get weather for a city.""" # This would normally call a w...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/snippets/servers/basic_tool.py", "license": "MIT License", "lines": 11, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
modelcontextprotocol/python-sdk:examples/snippets/servers/completion.py
from mcp.server.mcpserver import MCPServer from mcp.types import ( Completion, CompletionArgument, CompletionContext, PromptReference, ResourceTemplateReference, ) mcp = MCPServer(name="Example") @mcp.resource("github://repos/{owner}/{repo}") def github_repo(owner: str, repo: str) -> str: """...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/snippets/servers/completion.py", "license": "MIT License", "lines": 39, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
modelcontextprotocol/python-sdk:examples/snippets/servers/elicitation.py
"""Elicitation examples demonstrating form and URL mode elicitation. Form mode elicitation collects structured, non-sensitive data through a schema. URL mode elicitation directs users to external URLs for sensitive operations like OAuth flows, credential collection, or payment processing. """ import uuid from pydant...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/snippets/servers/elicitation.py", "license": "MIT License", "lines": 77, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
modelcontextprotocol/python-sdk:examples/snippets/servers/notifications.py
from mcp.server.mcpserver import Context, MCPServer from mcp.server.session import ServerSession mcp = MCPServer(name="Notifications Example") @mcp.tool() async def process_data(data: str, ctx: Context[ServerSession, None]) -> str: """Process data with logging.""" # Different log levels await ctx.debug(f...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/snippets/servers/notifications.py", "license": "MIT License", "lines": 14, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
modelcontextprotocol/python-sdk:examples/snippets/servers/sampling.py
from mcp.server.mcpserver import Context, MCPServer from mcp.server.session import ServerSession from mcp.types import SamplingMessage, TextContent mcp = MCPServer(name="Sampling Example") @mcp.tool() async def generate_poem(topic: str, ctx: Context[ServerSession, None]) -> str: """Generate a poem using LLM samp...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/snippets/servers/sampling.py", "license": "MIT License", "lines": 21, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
modelcontextprotocol/python-sdk:examples/snippets/servers/tool_progress.py
from mcp.server.mcpserver import Context, MCPServer from mcp.server.session import ServerSession mcp = MCPServer(name="Progress Example") @mcp.tool() async def long_running_task(task_name: str, ctx: Context[ServerSession, None], steps: int = 5) -> str: """Execute a task with progress updates.""" await ctx.in...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/snippets/servers/tool_progress.py", "license": "MIT License", "lines": 16, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
modelcontextprotocol/python-sdk:scripts/update_readme_snippets.py
#!/usr/bin/env python3 """Update README.md with live code snippets from example files. This script finds specially marked code blocks in README.md and updates them with the actual code from the referenced files. Usage: python scripts/update_readme_snippets.py python scripts/update_readme_snippets.py --check ...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "scripts/update_readme_snippets.py", "license": "MIT License", "lines": 126, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
modelcontextprotocol/python-sdk:tests/client/test_output_schema_validation.py
import logging from typing import Any import pytest from mcp import Client from mcp.server import Server, ServerRequestContext from mcp.types import ( CallToolRequestParams, CallToolResult, ListToolsResult, PaginatedRequestParams, TextContent, Tool, ) def _make_server( tools: list[Tool],...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "tests/client/test_output_schema_validation.py", "license": "MIT License", "lines": 134, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
modelcontextprotocol/python-sdk:examples/servers/simple-auth/mcp_simple_auth/simple_auth_provider.py
"""Simple OAuth provider for MCP servers. This module contains a basic OAuth implementation using hardcoded user credentials for demonstration purposes. No external authentication provider is required. NOTE: this is a simplified example for demonstration purposes. This is not a production-ready implementation. """ ...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/servers/simple-auth/mcp_simple_auth/simple_auth_provider.py", "license": "MIT License", "lines": 221, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
modelcontextprotocol/python-sdk:src/mcp/shared/auth_utils.py
"""Utilities for OAuth 2.0 Resource Indicators (RFC 8707) and PKCE (RFC 7636).""" import time from urllib.parse import urlparse, urlsplit, urlunsplit from pydantic import AnyUrl, HttpUrl def resource_url_from_server_url(url: str | HttpUrl | AnyUrl) -> str: """Convert server URL to canonical resource URL per RFC...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "src/mcp/shared/auth_utils.py", "license": "MIT License", "lines": 59, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
modelcontextprotocol/python-sdk:tests/shared/test_auth_utils.py
"""Tests for OAuth 2.0 Resource Indicators utilities.""" from pydantic import HttpUrl from mcp.shared.auth_utils import check_resource_allowed, resource_url_from_server_url # Tests for resource_url_from_server_url function def test_resource_url_from_server_url_removes_fragment(): """Fragment should be removed ...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "tests/shared/test_auth_utils.py", "license": "MIT License", "lines": 85, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
modelcontextprotocol/python-sdk:examples/servers/simple-auth/mcp_simple_auth/auth_server.py
"""Authorization Server for MCP Split Demo. This server handles OAuth flows, client registration, and token issuance. Can be replaced with enterprise authorization servers like Auth0, Entra ID, etc. NOTE: this is a simplified example for demonstration purposes. This is not a production-ready implementation. """ imp...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/servers/simple-auth/mcp_simple_auth/auth_server.py", "license": "MIT License", "lines": 140, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
modelcontextprotocol/python-sdk:examples/servers/simple-auth/mcp_simple_auth/legacy_as_server.py
"""Legacy Combined Authorization Server + Resource Server for MCP. This server implements the old spec where MCP servers could act as both AS and RS. Used for backwards compatibility testing with the new split AS/RS architecture. NOTE: this is a simplified example for demonstration purposes. This is not a production-...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/servers/simple-auth/mcp_simple_auth/legacy_as_server.py", "license": "MIT License", "lines": 106, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
modelcontextprotocol/python-sdk:examples/servers/simple-auth/mcp_simple_auth/token_verifier.py
"""Example token verifier implementation using OAuth 2.0 Token Introspection (RFC 7662).""" import logging from typing import Any from mcp.server.auth.provider import AccessToken, TokenVerifier from mcp.shared.auth_utils import check_resource_allowed, resource_url_from_server_url logger = logging.getLogger(__name__)...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/servers/simple-auth/mcp_simple_auth/token_verifier.py", "license": "MIT License", "lines": 86, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
modelcontextprotocol/python-sdk:src/mcp/server/transport_security.py
"""DNS rebinding protection for MCP server transports.""" import logging from pydantic import BaseModel, Field from starlette.requests import Request from starlette.responses import Response logger = logging.getLogger(__name__) # TODO(Marcelo): We should flatten these settings. To be fair, I don't think we should ...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "src/mcp/server/transport_security.py", "license": "MIT License", "lines": 87, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
modelcontextprotocol/python-sdk:tests/server/test_sse_security.py
"""Tests for SSE server DNS rebinding protection.""" import logging import multiprocessing import socket import httpx import pytest import uvicorn from starlette.applications import Starlette from starlette.requests import Request from starlette.responses import Response from starlette.routing import Mount, Route fr...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "tests/server/test_sse_security.py", "license": "MIT License", "lines": 232, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
modelcontextprotocol/python-sdk:tests/server/test_streamable_http_security.py
"""Tests for StreamableHTTP server DNS rebinding protection.""" import multiprocessing import socket from collections.abc import AsyncGenerator from contextlib import asynccontextmanager import httpx import pytest import uvicorn from starlette.applications import Starlette from starlette.routing import Mount from sta...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "tests/server/test_streamable_http_security.py", "license": "MIT License", "lines": 236, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
modelcontextprotocol/python-sdk:src/mcp/shared/metadata_utils.py
"""Utility functions for working with metadata in MCP types. These utilities are primarily intended for client-side usage to properly display human-readable names in user interfaces in a spec-compliant way. """ from mcp.types import Implementation, Prompt, Resource, ResourceTemplate, Tool def get_display_name(obj: ...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "src/mcp/shared/metadata_utils.py", "license": "MIT License", "lines": 37, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
modelcontextprotocol/python-sdk:src/mcp/server/elicitation.py
"""Elicitation utilities for MCP servers.""" from __future__ import annotations import types from collections.abc import Sequence from typing import Generic, Literal, TypeVar, Union, get_args, get_origin from pydantic import BaseModel from mcp.server.session import ServerSession from mcp.types import RequestId Eli...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "src/mcp/server/elicitation.py", "license": "MIT License", "lines": 144, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
modelcontextprotocol/python-sdk:tests/server/test_completion_with_context.py
"""Tests for completion handler with context functionality.""" import pytest from mcp import Client from mcp.server import Server, ServerRequestContext from mcp.types import ( CompleteRequestParams, CompleteResult, Completion, PromptReference, ResourceTemplateReference, ) @pytest.mark.anyio asyn...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "tests/server/test_completion_with_context.py", "license": "MIT License", "lines": 126, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
modelcontextprotocol/python-sdk:tests/issues/test_malformed_input.py
# Claude Debug """Test for HackerOne vulnerability report #3156202 - malformed input DOS.""" import anyio import pytest from mcp.server.models import InitializationOptions from mcp.server.session import ServerSession from mcp.shared.message import SessionMessage from mcp.types import INVALID_PARAMS, JSONRPCError, JSO...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "tests/issues/test_malformed_input.py", "license": "MIT License", "lines": 128, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
modelcontextprotocol/python-sdk:examples/clients/simple-auth-client/mcp_simple_auth_client/main.py
#!/usr/bin/env python3 """Simple MCP client example with OAuth authentication support. This client connects to an MCP server using streamable HTTP transport with OAuth. """ from __future__ import annotations as _annotations import asyncio import os import socketserver import threading import time import webbrowser ...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/clients/simple-auth-client/mcp_simple_auth_client/main.py", "license": "MIT License", "lines": 316, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
modelcontextprotocol/python-sdk:tests/client/test_auth.py
"""Tests for refactored OAuth client authentication implementation.""" import base64 import time from unittest import mock from urllib.parse import parse_qs, quote, unquote, urlparse import httpx import pytest from inline_snapshot import Is, snapshot from pydantic import AnyHttpUrl, AnyUrl from mcp.client.auth impor...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "tests/client/test_auth.py", "license": "MIT License", "lines": 1877, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
modelcontextprotocol/python-sdk:tests/client/test_list_methods_cursor.py
from collections.abc import Callable import pytest from mcp import Client, types from mcp.server import Server, ServerRequestContext from mcp.server.mcpserver import MCPServer from mcp.types import ListToolsResult from .conftest import StreamSpyCollection pytestmark = pytest.mark.anyio @pytest.fixture async def f...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "tests/client/test_list_methods_cursor.py", "license": "MIT License", "lines": 95, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
modelcontextprotocol/python-sdk:tests/shared/test_progress_notifications.py
from typing import Any from unittest.mock import patch import anyio import pytest from mcp import Client, types from mcp.client.session import ClientSession from mcp.server import Server, ServerRequestContext from mcp.server.lowlevel import NotificationOptions from mcp.server.models import InitializationOptions from ...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "tests/shared/test_progress_notifications.py", "license": "MIT License", "lines": 226, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
modelcontextprotocol/python-sdk:src/mcp/client/session_group.py
"""SessionGroup concurrently manages multiple MCP session connections. Tools, resources, and prompts are aggregated across servers. Servers may be connected to or disconnected from at any point after initialization. This abstraction can handle naming collisions using a custom user-provided hook. """ import contextli...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "src/mcp/client/session_group.py", "license": "MIT License", "lines": 340, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
modelcontextprotocol/python-sdk:tests/client/test_session_group.py
import contextlib from unittest import mock import httpx import pytest import mcp from mcp import types from mcp.client.session_group import ( ClientSessionGroup, ClientSessionParameters, SseServerParameters, StreamableHttpParameters, ) from mcp.client.stdio import StdioServerParameters from mcp.share...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "tests/client/test_session_group.py", "license": "MIT License", "lines": 333, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
modelcontextprotocol/python-sdk:src/mcp/shared/_httpx_utils.py
"""Utilities for creating standardized httpx AsyncClient instances.""" from typing import Any, Protocol import httpx __all__ = ["create_mcp_http_client", "MCP_DEFAULT_TIMEOUT", "MCP_DEFAULT_SSE_READ_TIMEOUT"] # Default MCP timeout configuration MCP_DEFAULT_TIMEOUT = 30.0 # General operations (seconds) MCP_DEFAULT_...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "src/mcp/shared/_httpx_utils.py", "license": "MIT License", "lines": 73, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
modelcontextprotocol/python-sdk:tests/shared/test_httpx_utils.py
"""Tests for httpx utility functions.""" import httpx from mcp.shared._httpx_utils import create_mcp_http_client def test_default_settings(): """Test that default settings are applied correctly.""" client = create_mcp_http_client() assert client.follow_redirects is True assert client.timeout.connec...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "tests/shared/test_httpx_utils.py", "license": "MIT License", "lines": 15, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
modelcontextprotocol/python-sdk:src/mcp/server/streamable_http_manager.py
"""StreamableHTTP Session Manager for MCP servers.""" from __future__ import annotations import contextlib import logging from collections.abc import AsyncIterator from http import HTTPStatus from typing import TYPE_CHECKING, Any from uuid import uuid4 import anyio from anyio.abc import TaskStatus from starlette.req...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "src/mcp/server/streamable_http_manager.py", "license": "MIT License", "lines": 253, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
modelcontextprotocol/python-sdk:tests/server/test_streamable_http_manager.py
"""Tests for StreamableHTTPSessionManager.""" import json import logging from typing import Any from unittest.mock import AsyncMock, patch import anyio import httpx import pytest from starlette.types import Message from mcp import Client from mcp.client.streamable_http import streamable_http_client from mcp.server i...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "tests/server/test_streamable_http_manager.py", "license": "MIT License", "lines": 315, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
modelcontextprotocol/python-sdk:examples/servers/simple-auth/mcp_simple_auth/server.py
"""MCP Resource Server with Token Introspection. This server validates tokens via Authorization Server introspection and serves MCP resources. Demonstrates RFC 9728 Protected Resource Metadata for AS/RS separation. NOTE: this is a simplified example for demonstration purposes. This is not a production-ready implement...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/servers/simple-auth/mcp_simple_auth/server.py", "license": "MIT License", "lines": 127, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
modelcontextprotocol/python-sdk:src/mcp/shared/message.py
"""Message wrapper with metadata support. This module defines a wrapper type that combines JSONRPCMessage with metadata to support transport-specific features like resumability. """ from collections.abc import Awaitable, Callable from dataclasses import dataclass from typing import Any from mcp.types import JSONRPCM...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "src/mcp/shared/message.py", "license": "MIT License", "lines": 35, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
modelcontextprotocol/python-sdk:examples/servers/simple-streamablehttp/mcp_simple_streamablehttp/event_store.py
"""In-memory event store for demonstrating resumability functionality. This is a simple implementation intended for examples and testing, not for production use where a persistent storage solution would be more appropriate. """ import logging from collections import deque from dataclasses import dataclass from uuid i...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/servers/simple-streamablehttp/mcp_simple_streamablehttp/event_store.py", "license": "MIT License", "lines": 72, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "templa...
function_complex
modelcontextprotocol/python-sdk:src/mcp/client/streamable_http.py
"""Implements StreamableHTTP transport for MCP clients.""" from __future__ import annotations as _annotations import contextlib import logging from collections.abc import AsyncGenerator, Awaitable, Callable from contextlib import asynccontextmanager from dataclasses import dataclass import anyio import httpx from an...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "src/mcp/client/streamable_http.py", "license": "MIT License", "lines": 483, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
modelcontextprotocol/python-sdk:examples/servers/simple-streamablehttp-stateless/mcp_simple_streamablehttp_stateless/__main__.py
from .server import main if __name__ == "__main__": # Click will handle CLI arguments import sys sys.exit(main()) # type: ignore[call-arg]
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/servers/simple-streamablehttp-stateless/mcp_simple_streamablehttp_stateless/__main__.py", "license": "MIT License", "lines": 5, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition...
function_simple
modelcontextprotocol/python-sdk:examples/servers/simple-streamablehttp-stateless/mcp_simple_streamablehttp_stateless/server.py
import contextlib import logging from collections.abc import AsyncIterator import anyio import click import uvicorn from mcp import types from mcp.server import Server, ServerRequestContext from mcp.server.streamable_http_manager import StreamableHTTPSessionManager from starlette.applications import Starlette from sta...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/servers/simple-streamablehttp-stateless/mcp_simple_streamablehttp_stateless/server.py", "license": "MIT License", "lines": 127, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition...
function_complex
modelcontextprotocol/python-sdk:examples/servers/simple-streamablehttp/mcp_simple_streamablehttp/server.py
import contextlib import logging from collections.abc import AsyncIterator import anyio import click from mcp import types from mcp.server import Server, ServerRequestContext from mcp.server.streamable_http_manager import StreamableHTTPSessionManager from starlette.applications import Starlette from starlette.middlewa...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "examples/servers/simple-streamablehttp/mcp_simple_streamablehttp/server.py", "license": "MIT License", "lines": 152, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template":...
function_complex
modelcontextprotocol/python-sdk:src/mcp/server/auth/handlers/authorize.py
import logging from dataclasses import dataclass from typing import Any, Literal # TODO(Marcelo): We should drop the `RootModel`. from pydantic import AnyUrl, BaseModel, Field, RootModel, ValidationError # noqa: TID251 from starlette.datastructures import FormData, QueryParams from starlette.requests import Request f...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "src/mcp/server/auth/handlers/authorize.py", "license": "MIT License", "lines": 195, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
modelcontextprotocol/python-sdk:src/mcp/server/auth/handlers/metadata.py
from dataclasses import dataclass from starlette.requests import Request from starlette.responses import Response from mcp.server.auth.json_response import PydanticJSONResponse from mcp.shared.auth import OAuthMetadata, ProtectedResourceMetadata @dataclass class MetadataHandler: metadata: OAuthMetadata asy...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "src/mcp/server/auth/handlers/metadata.py", "license": "MIT License", "lines": 21, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
modelcontextprotocol/python-sdk:src/mcp/server/auth/handlers/register.py
import secrets import time from dataclasses import dataclass from typing import Any from uuid import uuid4 from pydantic import BaseModel, ValidationError from starlette.requests import Request from starlette.responses import Response from mcp.server.auth.errors import stringify_pydantic_error from mcp.server.auth.js...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "src/mcp/server/auth/handlers/register.py", "license": "MIT License", "lines": 116, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
modelcontextprotocol/python-sdk:src/mcp/server/auth/handlers/revoke.py
from dataclasses import dataclass from functools import partial from typing import Any, Literal from pydantic import BaseModel, ValidationError from starlette.requests import Request from starlette.responses import Response from mcp.server.auth.errors import ( stringify_pydantic_error, ) from mcp.server.auth.json...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "src/mcp/server/auth/handlers/revoke.py", "license": "MIT License", "lines": 72, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
modelcontextprotocol/python-sdk:src/mcp/server/auth/handlers/token.py
import base64 import hashlib import time from dataclasses import dataclass from typing import Annotated, Any, Literal from pydantic import AnyHttpUrl, AnyUrl, BaseModel, Field, TypeAdapter, ValidationError from starlette.requests import Request from mcp.server.auth.errors import stringify_pydantic_error from mcp.serv...
{ "repo_id": "modelcontextprotocol/python-sdk", "file_path": "src/mcp/server/auth/handlers/token.py", "license": "MIT License", "lines": 184, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex