MCP 개요

MCP 개요 (Overview)

LiteLLM Proxy는 모든 MCP 도구에 고정 엔드포인트를 사용하고 키·팀으로 MCP 접근을 제어할 수 있게 해주는 MCP 게이트웨이를 제공해요.

LiteLLM MCP 아키텍처: LiteLLM이 지원하는 모든 모델과 MCP 도구를 함께 사용

개요 (Overview)

기능 설명
MCP 작업 • 도구 목록(List Tools)
• 도구 호출(Call Tools)
• 프롬프트(Prompts)
• 리소스(Resources)
직접 REST API /mcp-rest/tools/list/mcp-rest/tools/call — LLM 없이 curl로 도구 호출
지원 MCP 전송 • Streamable HTTP
• SSE
• Standard Input/Output (stdio)
LiteLLM 권한 관리 • 키(Key)별
• 팀(Team)별
• 조직(Organization)별

MCP 프로토콜 업데이트 — 게이트웨이는 initialize 중 프로토콜 버전을 협상해요. 테스트된 버전과 기능 한계 참고.

LiteLLM은 각 도구 이름에 MCP 서버 이름을 접두사로 붙여 여러 MCP 서버를 네임스페이싱하므로, 새로 만드는 서버는 SEP-986을 준수하는 이름을 사용해야 해요. 비준수 이름은 더 이상 추가할 수 없어요. SEP-986을 여전히 위반하는 기존 서버는 오늘 경고만 내지만, 향후 MCP 쪽 롤아웃이 그 이름을 완전히 차단할 수 있으므로 MCP 강제가 적용되기 전에 기존 서버 이름을 사전에 업데이트하는 것을 권장해요.

어떤 엔드포인트, 전송, 인증 패턴을 쓸지에 대한 단일 결정 참조는 MCP Configuration Reference를 참고하세요.

출처: 문서

본문

MCP 추가 (Adding your MCP)

사전 요구사항 (Prerequisites)

MCP 서버를 데이터베이스에 저장하려면 데이터베이스 저장을 활성화해야 해요:

환경 변수:

export STORE_MODEL_IN_DB=True

또는 config.yaml에서:

general_settings:
  store_model_in_db: true

세밀한 데이터베이스 저장 제어 (Fine-grained Database Storage Control)

기본적으로 store_model_in_dbtrue이면 모든 객체 유형(모델, MCP, 가드레일, 벡터 저장소 등)이 데이터베이스에 저장돼요. 특정 객체 유형만 저장하려면 supported_db_objects 설정을 사용하세요.

예시: 데이터베이스에 MCP 서버만 저장

config.yaml:

general_settings:
  store_model_in_db: true
  supported_db_objects: ["mcp"]  # Only store MCP servers in DB

model_list:
  - model_name: gpt-5.6-terra
    litellm_params:
      model: openai/gpt-5.6-terra
      api_key: sk-xxxxxxx

사용 가능한 모든 객체 유형 보기: Config Settings - supported_db_objects

supported_db_objects가 설정되지 않으면 모든 객체 유형이 데이터베이스에서 로드돼요(기본 동작).

설정 후 연결 문제 진단은 MCP Troubleshooting Guide의 5분 분류증상 매트릭스부터 시작하세요.

LiteLLM UI: LiteLLM UI에서 "MCP Servers"로 이동해 "Add New MCP Server" 클릭. 이 폼에서 MCP Server URL과 사용할 전송을 입력해요. LiteLLM은 다음 MCP 전송을 지원해요:

  • Streamable HTTP
  • SSE (Server-Sent Events)
  • Standard Input/Output (stdio)

HTTP MCP 서버 추가

이 비디오는 LiteLLM UI에서 HTTP MCP 서버를 추가·사용하고 Cursor IDE에서 사용하는 방법을 안내해요.

SSE MCP 서버 추가

이 비디오는 LiteLLM UI에서 SSE MCP 서버를 추가·사용하고 Cursor IDE에서 사용하는 방법을 안내해요.

STDIO MCP 서버 추가

stdio MCP 서버의 경우 전송 타입으로 "Standard Input/Output (stdio)"을 선택하고 stdio 구성을 JSON 형식으로 제공하세요.

OAuth 구성 및 오버라이드 (OAuth Configuration & Overrides)

LiteLLM은 기본적으로 OAuth 2.0 Authorization Server Discovery를 시도해요. UI에서 MCP 서버를 생성하고 Authentication: OAuth로 설정하면 LiteLLM이 프로바이더 메타데이터를 찾고 클라이언트를 동적 등록하며 추가 세부 정보 제공 없이 PKCE 기반 인증을 수행해요.

필요할 때 OAuth 흐름 커스터마이징:

  • 명시적 클라이언트 자격 증명 제공 — MCP 프로바이더가 동적 클라이언트 등록을 제공하지 않거나 클라이언트를 직접 관리하고 싶다면 client_id, client_secret, 원하는 scopes를 채우세요.
  • 디스커버리 URL 재정의 — 일부 환경에서 LiteLLM이 프로바이더 메타데이터 엔드포인트에 도달하지 못할 수 있어요. 선택적 authorization_url, token_url, registration_url 필드로 LiteLLM을 올바른 엔드포인트로 직접 가리키세요.

AWS SigV4 인증

AWS Bedrock AgentCore에 호스팅된 MCP 서버의 경우 인증 타입으로 AWS SigV4를 선택하세요. LiteLLM이 Signature Version 4로 AWS 자격 증명을 사용해 모든 아웃바운드 MCP 요청을 서명해요.

AWS 리전, 서비스 이름(기본값 bedrock-agentcore), 선택적으로 AWS 액세스 키와 시크릿을 입력하세요. 자격 증명이 생략되면 LiteLLM이 boto3 자격 증명 체인으로 폴백해요(IAM 역할, 환경 변수 등).

전체 SigV4 설정 가이드

정적 헤더 (Static Headers)

때로 MCP 서버가 모든 요청에 특정 헤더가 필요할 수 있어요. API 키일 수도, 서버가 기대하는 사용자 지정 헤더일 수도 있어요. auth를 구성하는 대신 직접 설정할 수 있어요.

이 헤더들은 서버에 대한 모든 요청과 함께 보내져요. 그게 전부예요.

사용 시점:

  • 서버가 표준 인증 패턴에 맞지 않는 사용자 지정 헤더가 필요할 때
  • 정확히 어떤 헤더가 보내지는지 완전히 제어하고 싶을 때
  • 인증 구성을 바꾸지 않고 디버깅 중에 헤더를 빠르게 추가해야 할 때

서버 변수 (Server Variables)

${VAR_NAME}(예: ${DB_PROTOCOL}://${CORP_USERNAME}:${CORP_PASSWORD}@${DB_HOSTNAME})로 서버에 자격 증명을 저장하고 정적 헤더나 인증에서 참조하세요. 각 변수를 Instance(공유) 또는 Per-user(각 사용자가 자체 공급)로 범위를 지정하세요.

사용 시점:

  • 각 사용자가 자체 정적 자격 증명으로 연결해야 할 때
  • 공유 세부 사항(예: DB url)을 사용자 간에 재사용하고 싶을 때

config.yaml:

MCP 서버를 config.yaml 파일에 직접 추가하세요:

model_list:
  - model_name: gpt-5.6-terra
    litellm_params:
      model: openai/gpt-5.6-terra
      api_key: «redacted:sk-…»

litellm_settings:
  # MCP Aliases - Map aliases to server names for easier tool access
  mcp_aliases:
    "github": "github_mcp_server"
    "zapier": "zapier_mcp_server"
    "deepwiki": "deepwiki_mcp_server"

mcp_servers:
  # HTTP Streamable Server
  deepwiki_mcp:
    url: "https://mcp.deepwiki.com/mcp"
  # SSE Server
  zapier_mcp:
    url: "https://actions.zapier.com/mcp/sk-akxxxxx/sse"
  
  # Standard Input/Output (stdio) Server - CircleCI Example
  circleci_mcp:
    transport: "stdio"
    command: "npx"
    args: ["-y", "@circleci/mcp-server-circleci"]
    env:
      CIRCLECI_TOKEN: "your-circleci-token"
      CIRCLECI_BASE_URL: "https://circleci.com"
  
  # Full configuration with all optional fields
  my_http_server:
    url: "https://my-mcp-server.com/mcp"
    transport: "http"
    description: "My custom MCP server"
    auth_type: "api_key"
    auth_value: "abc123"

구성 옵션 (Configuration Options):

  • Server Name: MCP 서버에 어떤 설명적 이름이든 사용(예: zapier_mcp, deepwiki_mcp, circleci_mcp)
  • server_id: 서버용 선택적 안정 id. Pinning server_id 참고
  • Alias: 이 이름은 공백을 "_"로 바꾼 서버 이름으로 미리 채워지며, 도구 이름의 접두사가 되도록 편집 가능
  • URL: MCP 서버의 엔드포인트 URL(HTTP/SSE 전송에 필수)
  • Transport: config.yaml에서 기본값 http. 관리 API 요청 모델은 기본값 sse. 서버 추가·업데이트 시 명시적으로 설정하세요. transport defaults 참고
    • sse — SSE (Server-Sent Events) 전송
    • http — Streamable HTTP 전송
    • stdio — Standard Input/Output 전송
  • Command: stdio 전송용 실행 명령(stdio에 필수)
  • allow_all_keys: true로 설정하면 키/팀이 MCP 권한에 서버를 나열하지 않아도 모든 LiteLLM API 키에 서버를 사용 가능하게 해요.
  • Args: 명령에 전달할 인자 배열(stdio 선택)
  • Env: stdio 프로세스용 환경 변수(stdio 선택)
  • Description: 서버용 선택적 설명
  • Auth Type: 선택적 인증 타입. 지원 값:

선택 가이드, 정확한 자격 증명 입력, 업스트림 요청 예시는 MCP Non-OAuth Authentication 참고.

보내는 헤더(관리 SSE/HTTP 전송)
none 인증 헤더 추가 없음
api_key X-API-Key: ***
bearer_token Authorization: Bearer ***
basic Authorization: Basic <base6...)>; auth_value를 원시 username:password로 입력
authorization Authorization: ***(그대로, 접두사 없음)
token Authorization: token ***(GitHub 스타일)
oauth2 Authorization: Bearer *** — PKCE 또는 M2M client_credentials. MCP OAuth 참고
oauth2_token_exchange Authorization: Bearer <excha...en> — RFC 8693 On-Behalf-Of. MCP OBO Auth 참고
oauth2_id_jag Authorization: Bearer *** — Identity Assertion Authorization Grant(두 다리). MCP ID-JAG Auth 참고
true_passthrough 클라이언트의 업스트림 Authorization, 그대로 전달. MCP OAuth Passthrough 참고
oauth_delegate LiteLLM 입장 후 별개 클라이언트 공급 업스트림 베어러. MCP OAuth Passthrough 참고
aws_sigv4 요청별 AWS SigV4 서명. MCP AWS SigV4 참고

위 헤더는 기본값이에요. 서버에 upstream_token_header를 설정하면 해석된 토큰을 Authorization이 아닌 다른 곳으로 보내며, 이는 보통 API 게이트웨이 뒤의 MCP 서버가 필요로 하는 것입니다. MCP OAuth 참고.

참고: 위 헤더 표는 관리 SSE/HTTP 전송 경로를 설명해요. OpenAPI 도구 경로는 auth_type: api_key에 대해 X-API-Key 대신 Authorization: ApiKey ***를 내보내요. 더 이상 사용하지 않는 x-mcp-auth 브로드캐스트 헤더도 ApiKey 형태를 사용해요.

  • Extra Headers: 클라이언트에서 MCP 서버로 전달해야 하는 추가 헤더 이름의 선택적 목록
  • Static Headers: MCP 서버에 대한 모든 요청에 포함할 헤더 키/값 쌍의 선택적 맵

auth_type: oauth2에는 oauth2_flow가 필요해요. 서비스 신원에는 client_credentials, 사용자별 로그인에는 authorization_code를 사용하세요. 누락되거나 잘못된 흐름은 프록시 시작을 막아요. MCP OAuth 참고.

각 auth 타입의 예시:

MCP auth 예시 (config.yaml):

mcp_servers:
  api_key_example:
    url: "https://my-mcp-server.com/mcp"
    auth_type: "api_key"
    auth_value: "abc123"        # headers={"X-API-Key": "abc123"}

  # OAuth 2.0 client credentials (machine-to-machine)
  oauth2_example:
    url: "https://my-mcp-server.com/mcp"
    transport: "http"
    auth_type: "oauth2"
    oauth2_flow: "client_credentials"
    token_url: "https://my-mcp-server.com/oauth/token"
    client_id: os.environ/OAUTH_CLIENT_ID
    client_secret: os.environ/OAUTH_CLIENT_SECRET
    scopes: ["tool.read", "tool.write"] # optional override

  bearer_example:
    url: "https://my-mcp-server.com/mcp"
    auth_type: "bearer_token"
    auth_value: "abc123"        # headers={"Authorization": "Bearer abc123"}

  basic_example:
    url: "https://my-mcp-server.com/mcp"
    auth_type: "basic"
    auth_value: "user:pass"  # headers={"Authorization": "Basic dXNlcjpwYXNz"}

  custom_auth_example:
    url: "https://my-mcp-server.com/mcp"
    auth_type: "authorization"
    auth_value: "Token example123"  # headers={"Authorization": "Token example123"}

  # AWS SigV4 for Bedrock AgentCore MCP servers
  agentcore_mcp:
    url: "https://bedrock-agentcore.us-east-1.amazonaws.com/runtimes/<url-encoded-ARN>/invocations"
    transport: "http"
    auth_type: "aws_sigv4"
    aws_role_name: os.environ/AWS_ROLE_ARN          # optional — IAM role to assume
    aws_access_key_id: os.environ/AWS_ACCESS_KEY_ID  # optional — falls back to IAM role
    aws_secret_access_key: os.environ/AWS_SECRET_ACCESS_KEY
    aws_region_name: us-east-1
    aws_service_name: bedrock-agentcore

  # Example with extra headers forwarding
  github_mcp:
    url: "https://api.githubcopilot.com/mcp"
    auth_type: "bearer_token"
    auth_value: "ghp_example_token"
    extra_headers: ["custom_key", "x-custom-header"]  # These headers will be forwarded from client

  # Example with static headers
  my_mcp_server:
    url: "https://my-mcp-server.com/mcp"
    static_headers: # These headers will be requested to the MCP server
      X-API-Key: ***
      X-Custom-Header: "some-value"

server_id 고정 (Pinning server_id)

LiteLLM은 config 서버의 id를 이름과 연결 설정에서 파생해요. 그 설정들을 바꾸면 id가 바뀌고 기존 키·팀 권한이 더 이상 일치하지 않게 돼요.

서버가 바뀔 때 같은 id를 유지하려면 server_id를 설정하세요:

mcp_servers:
  internal_docs:
    server_id: "internal-docs"
    url: "https://docs.internal.example/mcp"
    transport: "http"

서버에 이미 권한이 있으면 GET /v1/mcp/server 또는 관리 UI에서 현재 id를 얻은 후 그 정확한 값을 server_id로 설정하세요:

curl -s http://localhost:4000/v1/mcp/server \
  -H "Authorization: Bearer ***"

server_id는 비어 있지 않은 문자열이어야 해요. config 항목은 다른 항목의 id나 이름·별칭을 재사용할 수 없어요. 데이터베이스 지원 서버와의 충돌은 경고만 로깅해요. id가 일치하면 데이터베이스 서버가 우선하고 config 서버는 도달할 수 없으며, 그 서버의 이름·별칭과 일치하면 그것을 지정한 권한이 config 서버에 도달해요.

LITELLM_USE_SHORT_MCP_TOOL_PREFIX가 활성화되면 id 변경이 서버의 도구 접두사도 바꿔요. UI 또는 /v1/mcp/server로 추가한 서버는 이미 안정 id를 가져요.

MCP 워크스루 (MCP Walkthroughs)

UI에서 추가:

{
  "mcpServers": {
    "strands-agents": {
      "command": "uvx",
      "args": ["strands-agents-mcp-server"],
      "env": {
        "FASTMCP_LOG_LEVEL": "INFO"
      },
      "disabled": false,
      "autoApprove": ["search_docs", "fetch_doc"]
    }
  }
}

config.yml:

mcp_servers:
  strands_mcp:
    transport: "stdio"
    command: "uvx"
    args: ["strands-agents-mcp-server"]
    env:
      FASTMCP_LOG_LEVEL: "INFO"

MCP 별칭 (MCP Aliases)

litellm_settings 섹션에서 MCP 서버의 별칭을 정의할 수 있어요. 이를 통해:

  1. 친근한 이름을 서버 이름에 매핑: 더 짧고 기억하기 쉬운 별칭 사용
  2. 서버 별칭 재정의: 서버에 별칭이 정의되지 않았다면 시스템이 mcp_aliases의 첫 일치 별칭을 사용
  3. 고유성 보장: 각 서버의 첫 별칭만 사용되어 충돌 방지

예시:

litellm_settings:
  mcp_aliases:
    "github": "github_mcp_server"      # Maps "github" alias to "github_mcp_server"
    "zapier": "zapier_mcp_server"      # Maps "zapier" alias to "zapier_mcp_server"
    "docs": "deepwiki_mcp_server"      # Maps "docs" alias to "deepwiki_mcp_server"
    "github_alt": "github_mcp_server"  # This will be ignored since "github" already maps to this server

이점:

  • 단순화된 도구 접근: github_mcp_server_create_issue 대신 github_create_issue 사용
  • 일관된 명명: 조직 전체에 별칭 패턴 표준화
  • 쉬운 마이그레이션: 기존 도구 참조를 깨지 않고 서버 이름 변경

OpenAPI 스펙을 MCP 서버로 변환 (Converting OpenAPI Specs to MCP Servers)

LiteLLM은 OpenAPI 스펙을 MCP 서버로 변환해 사용자 지정 서버 코드 없이 REST API를 MCP 도구로 노출할 수 있어요.

전체 설정, 사용 예시, 도구 이름·설명 재정의 방법은 MCP from OpenAPI Specs 가이드 참고.

MCP OAuth

LiteLLM은 MCP 서버용 OAuth 2.0을 지원해요. 사용자 대면 클라이언트용 interactive(PKCE) 흐름과 백엔드 서비스용 M2M client_credentials가 모두요.

설정 지침, 시퀀스 다이어그램, 테스트 서버는 MCP OAuth 가이드 참고.

상세 OAuth 참조 (클릭해 펼치기)

LiteLLM v1.77.6은 MCP 서버용 OAuth 2.0 Client Credentials 지원을 추가했어요.

config.yaml이나 LiteLLM UI(MCP Servers → Authentication → OAuth)에서 직접 구성할 수 있어요. 모든 auth_type: oauth2 서버는 oauth2_flow로 흐름을 선언해야 해요. 대화형 브라우저 로그인(아래)에는 authorization_code, machine-to-machine 토큰에는 client_credentials.

mcp_servers:
  github_mcp:
    url: "https://api.githubcopilot.com/mcp"
    auth_type: oauth2
    oauth2_flow: authorization_code
    client_id: os.environ/GITHUB_OAUTH_CLIENT_ID
    client_secret: os.environ/GITHUB_OAUTH_CLIENT_SECRET

Claude Code Tutorial 참고

동작 방식 (How It Works)

참여자 (Participants)

  • Client — 사용자를 대신해 OAuth 디스커버리, 인증, 도구 호출을 시작하는 MCP 가능 AI 에이전트(예: Claude Code, Cursor, 다른 IDE/에이전트).
  • LiteLLM Proxy — 저장된 자격 증명을 보호하면서 모든 OAuth 디스커버리, 등록, 토큰 교환, MCP 트래픽을 중재.
  • Authorization Server — 동적 클라이언트 등록, PKCE 인증, 토큰 엔드포인트로 OAuth 2.0 토큰 발행.
  • MCP Server (Resource Server) — LiteLLM의 인증된 JSON-RPC 요청을 받는 보호된 MCP 엔드포인트.
  • User-Agent (Browser) — 인증 단계에서 최종 사용자가 동의를 부여하도록 일시적으로 관여.

흐름 단계 (Flow Steps)

  1. 리소스 디스커버리: 클라이언트가 LiteLLM의 .well-known/oauth-protected-resource 엔드포인트에서 MCP 리소스 메타데이터를 가져와 스코프와 기능을 이해.
  2. Authorization Server 디스커버리: 클라이언트가 LiteLLM의 .well-known/oauth-authorization-server 엔드포인트를 통해 OAuth 서버 메타데이터(토큰 엔드포인트, 인증 엔드포인트, 지원 PKCE 메서드)를 검색.
  3. Dynamic Client Registration: 클라이언트가 LiteLLM을 통해 등록. LiteLLM은 요청을 authorization server로 전달(RFC 7591). 프로바이더가 동적 등록을 지원하지 않으면 client_id/client_secret을 사전 저장(예: GitHub MCP)하고 흐름은 같은 방식으로 진행.
  4. 사용자 인증: 클라이언트가 브라우저 세션(code challenge와 리소스 힌트 포함) 시작. 사용자가 접근을 승인하고 authorization server가 code를 LiteLLM을 통해 클라이언트로 보냄.
  5. 토큰 교환: 클라이언트가 authorization code, code verifier, 리소스로 LiteLLM 호출. LiteLLM이 authorization server와 교환하고 발행된 access/refresh 토큰 반환.
  6. MCP 호출: 유효한 토큰으로 클라이언트가 MCP JSON-RPC 요청(플러스 LiteLLM API 키)을 LiteLLM에 보내고, LiteLLM이 그것을 MCP 서버로 전달하며 도구 응답을 중계.

추가 참조: 공식 MCP Authorization Flow.

MCP 서버로 사용자 지정 헤더 전달 (Forwarding Custom Headers to MCP Servers)

LiteLLM은 extra_headers 구성 파라미터로 MCP 클라이언트의 추가 사용자 지정 헤더를 백엔드 MCP 서버로 전달하는 것을 지원해요. MCP 서버가 요구하는 사용자 지정 인증 토큰, API 키, 다른 헤더를 전달할 수 있게 해줘요.

구성:

extra_headers에서 전달할 헤더 이름을 지정하세요:

extra_headers가 있는 config.yaml:

mcp_servers:
  github_mcp:
    url: "https://api.githubcopilot.com/mcp"
    auth_type: "bearer_token"
    auth_value: "ghp_default_token"
    extra_headers: ["custom_key", "x-custom-header", "Authorization"]
    description: "GitHub MCP server with custom header forwarding"

그룹 MCP 서버에 사용자 접근을 줄 때 사용하세요.

형식: x-mcp-{server_alias}-{header_name}: value

이를 통해 서로 다른 MCP 서버에 서로 다른 인증을 사용할 수 있어요.

예시:

  • x-mcp-github-authorization: Bearer *** — Bearer 토큰이 있는 GitHub MCP 서버
  • x-mcp-zapier-x-api-key: *** — API 키가 있는 Zapier MCP 서버
  • x-mcp-deepwiki-authorization: Basic base64...eds — Basic 인증이 있는 DeepWiki MCP 서버

접근 그룹의 모든 서버가 같은 자격 증명을 받는다면 x-mcp-{access_group}-{header_name}으로 한 번 보내고 LiteLLM이 access_groups에 그 그룹이 포함된 각 서버로 전달해요. 서버별 x-mcp-{server_alias}-{header_name} 헤더는 그 서버에서 여전히 우선하고, 그룹 밖의 서버는 그룹 자격 증명을 받지 않아요. 서버가 서로 다른 자격 증명을 가진 여러 그룹에 속하면 LiteLLM이 그중 어떤 것도 전달하지 않아요.

서버별 인증이 있는 Python 클라이언트:

from fastmcp import Client
import asyncio

# Standard MCP configuration with multiple servers
config = {
    "mcpServers": {
        "mcp_group": {
            "url": "http://localhost:4000/mcp/",
            "headers": {
                "x-mcp-servers": "dev_group", # assume this gives access to github, zapier and deepwiki
                "x-litellm-api-key": "Bearer sk-<your-litellm-api-key>",
                "x-mcp-github-authorization": "Bearer gho_token", 
                "x-mcp-zapier-x-api-key": "sk-xxxxxxxxx",
                "x-mcp-deepwiki-authorization": "Basic base64_encoded_creds",
                "custom_key": "value"
            }
        }
    }
}

# Create a client that connects to all servers
client = Client(config)


async def main():
    async with client:
        tools = await client.list_tools()
        print(f"Available tools: {tools}")

        # call mcp 
        await client.call_tool(
            name="github_mcp-search_issues",
            arguments={'query': 'created:>2024-01-01', 'sort': 'created', 'order': 'desc', 'perPage': 30}
        )

if __name__ == "__main__":
    asyncio.run(main())

이점:

  • 서버별 인증: 각 MCP 서버가 다른 인증 방법 사용 가능
  • 더 나은 보안: 모든 서버에 같은 인증 토큰을 공유할 필요 없음
  • 유연한 헤더 이름: 여러 인증 헤더 타입 지원(authorization, x-api-key 등)
  • 깨끗한 분리: 각 서버의 인증이 명확히 식별

클라이언트 사용 (Client Usage)

MCP 클라이언트에서 연결할 때 extra_headers 구성과 일치하는 사용자 지정 헤더를 포함하세요.

사용자 지정 헤더가 있는 FastMCP 클라이언트:

from fastmcp import Client
import asyncio

# MCP client configuration with custom headers
config = {
    "mcpServers": {
        "github": {
            "url": "http://localhost:4000/github_mcp/mcp",
            "headers": {
                "x-litellm-api-key": "Bearer sk-<your-litellm-api-key>",
                "Authorization": "Bearer gho_token", 
                "custom_key": "custom_value",
                "x-custom-header": "additional_data"
            }
        }
    }
}

# Create a client that connects to the server
client = Client(config)

async def main():
    async with client:
        # List available tools
        tools = await client.list_tools()
        print(f"Available tools: {tools}")
        
        # Call a tool if available
        if tools:
            result = await client.call_tool(tools[0].name, {})
            print(f"Tool result: {result}")

# Run the client
asyncio.run(main())

사용자 지정 헤더가 있는 Cursor 구성:

{
  "mcpServers": {
    "GitHub": {
      "url": "http://localhost:4000/github_mcp/mcp",
      "headers": {
        "x-litellm-api-key": "Bearer sk-<your-litellm-api-key>",
        "Authorization": "Bearer $GITHUB_TOKEN",
        "custom_key": "custom_value",
        "x-custom-header": "additional_data"
      }
    }
  }
}

사용자 지정 헤더가 있는 cURL:

curl --location 'http://localhost:4000/github_mcp/mcp' \
--header 'Content-Type: application/json' \
--header "x-litellm-api-key: *** $LITELLM_API_KEY" \
--header 'Authorization: Bearer ***' \
--header 'custom_key: custom_value' \
--header 'x-custom-header: additional_data' \
--data '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "tools/list"
}'

동작 방식 (How It Works)

  1. 구성: 전달할 헤더 이름으로 MCP 서버 config에 extra_headers 정의
  2. 클라이언트 헤더: MCP 클라이언트 요청에 해당 헤더를 포함
  3. 헤더 전달: LiteLLM이 일치하는 헤더를 백엔드 MCP 서버로 자동 전달
  4. 인증: 백엔드 MCP 서버가 구성된 인증 헤더와 사용자 지정 헤더를 모두 받음

요청 헤더를 STDIO env 변수에 전달 (Passing Request Headers to STDIO env Vars)

stdio MCP 서버가 요청별 자격 증명이 필요하다면 클라이언트 요청의 HTTP 헤더를 시작된 stdio 프로세스의 환경으로 직접 매핑할 수 있어요. env 값에서 ${X-HEADER_NAME} 구문으로 헤더 이름을 참조하세요. LiteLLM이 들어오는 요청에서 그 헤더를 읽고 명령을 시작하기 전에 env var를 설정해요.

X-GITHUB_PERSONAL_ACCESS_TOKEN 헤더를 stdio env로 전달:

{
  "mcpServers": {
    "github": {
      "command": "docker",
      "args": [
        "run",
        "-i",
        "--rm",
        "-e",
        "GITHUB_PERSONAL_ACCESS_TOKEN",
        "ghcr.io/github/github-mcp-server"
      ],
      "env": {
        "GITHUB_PERSONAL_ACCESS_TOKEN": "${X-GITHUB_PERSONAL_ACCESS_TOKEN}"
      }
    }
  }
}

이 예시에서 클라이언트가 X-GITHUB_PERSONAL_ACCESS_TOKEN 헤더로 요청하면 프록시가 그 값을 GITHUB_PERSONAL_ACCESS_TOKEN 환경 변수로 stdio 프로세스에 전달해요.

최종 사용자의 MCP 접근 제어 (Control MCP Access for End Users)

AI 애플리케이션(AI 앱의 최종 사용자, 예: 내부 채팅 UI 사용자)이 접근할 수 있는 MCP 서버를 제어하세요. x-litellm-end-user-id 헤더에 고객 ID를 전달하면:

  • 객체 권한 실행(접근할 수 있는 MCP 서버 제한)
  • 고객별 예산 적용
  • 고객별 지출 추적

FastMCP 클라이언트 예시:

from fastmcp import Client
import asyncio

# MCP client configuration with customer tracking
config = {
    "mcpServers": {
        "github": {
            "url": "http://localhost:4000/github_mcp/mcp",
            "headers": {
                "x-litellm-api-key": "Bearer sk-<your-litellm-api-key>",
                "x-litellm-end-user-id": "customer_123",  # 👈 CUSTOMER ID
                "Authorization": "Bearer gho_token"
            }
        }
    }
}

client = Client(config)

async def main():
    async with client:
        # All MCP calls will be tracked under customer_123
        tools = await client.list_tools()
        result = await client.call_tool(tools[0].name, {})
        print(f"Tool result: {result}")

asyncio.run(main())

Cursor IDE 예시:

{
  "mcpServers": {
    "GitHub": {
      "url": "http://localhost:4000/github_mcp/mcp",
      "headers": {
        "x-litellm-api-key": "Bearer sk-<your-litellm-api-key>",
        "x-litellm-end-user-id": "customer_123"
      }
    }
  }
}

무슨 일이 일어나나요 (What happens):

  • 고객별 객체 권한이 강제(허용된 MCP 서버만 접근 가능)
  • 고객 예산 적용
  • 모든 도구 호출이 customer_123 아래에 추적

고객 관리에 대해 자세히 알아보기 →

프록시의 /v1/responses 엔드포인트 호출 (Calling the Proxy's /v1/responses Endpoint)

LiteLLM Proxy의 /v1/responses 엔드포인트를 호출해 MCP 도구를 사용할 때 모든 허용 서버에는 server_url: "litellm_proxy"를, 한 서버에는 tools 배열에 litellm_proxy/mcp/<server_alias>를 사용하세요. 이는 프록시가 구성된 MCP 서버를 사용하도록 지시해요.

전체 프록시 URL을 쓰지 마세요 — 요청이 이미 프록시로 가고 있을 때 server_url: "https://your-proxy.com/mcp"는 올바르지 않아요. 구성된 MCP 서버로 라우팅하려면 문서화된 센티널 형태를 사용하세요. 직접 MCP 클라이언트는 네트워크 URL을 대신 사용해요.

올바름: litellm_proxy 사용:

curl --location 'https://your-proxy.com/v1/responses' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer ***" \
--data '{
    "model": "gpt-5.6-terra",
    "tools": [
        {
            "type": "mcp",
            "server_label": "litellm",
            "server_url": "litellm_proxy",
            "require_approval": "never"
        }
    ],
    "input": "Run available tools",
    "tool_choice": "required"
}'

MCP 서버로 사용자 지정 헤더 보내기 (Sending Custom Headers to MCP Servers)

특정 MCP 서버에 사용자 지정 헤더(예: API 키, 인증 토큰)를 전달하려면 다음 중 하나를 사용하세요:

옵션 1: 요청 헤더 — 요청 헤더에 x-mcp-{server_alias}-{header_name} 추가. 프록시가 일치하는 MCP 서버로 전달해요.

# Send Authorization header to the "weather2" MCP server
--header 'x-mcp-weather2-authorization: Bearer ***'

# Send custom header to the "github" MCP server  
--header 'x-mcp-github-x-api-key: ***

옵션 2: 도구 구성의 헤더 — 도구 정의에 headers 객체 포함. 이것들은 요청 헤더와 병합돼요.

{
    "type": "mcp",
    "server_label": "litellm",
    "server_url": "litellm_proxy",
    "require_approval": "never",
    "headers": {
        "x-litellm-api-key": "Bearer YOUR_LITELLM_API_KEY",
        "x-mcp-servers": "Zapier_MCP,dev-group",
        "x-mcp-weather2-authorization": "Bearer your-weather-api-token"
    }
}

클라이언트 측 자격 증명으로 MCP 사용 (Using your MCP with client side credentials)

클라이언트 측 인증 토큰을 LiteLLM에 전달해 MCP에 인증하려면 이것을 사용하세요.

x-mcp-{server_alias}-{header_name} 형식의 서버별 헤더로 MCP 인증 토큰을 지정할 수 있어요. 서로 다른 MCP 서버에 서로 다른 인증을 사용하게 해줘요.

이점:

  • 서버별 인증: 각 MCP 서버가 다른 인증 방법 사용 가능
  • 더 나은 보안: 모든 서버에 같은 인증 토큰을 공유할 필요 없음
  • 유연한 헤더 이름: 여러 인증 헤더 타입 지원(authorization, x-api-key 등)
  • 깨끗한 분리: 각 서버의 인증이 명확히 식별

그룹 레벨 인증 헤더 (Group-Level Auth Headers)

접근 그룹의 서버들이 하나의 자격 증명을 공유할 때 서버마다 반복하는 대신 x-mcp-{access_group}-{header_name}을 한 번 전달하세요. LiteLLM이 access_groups에 그 그룹이 포함된 모든 서버의 기본값으로 사용해요. 서버별 x-mcp-{server_alias}-{header_name} 헤더가 그 서버에서 재정의하고, 그룹 밖의 서버는 결코 받지 않으며, 서버가 서로 다른 자격 증명을 가진 여러 그룹에 있으면 어떤 것도 전달되지 않아요. 서버 별칭과 접근 그룹 이름은 x-mcp- 헤더 네임스페이스를 공유하므로, 별칭이 그룹 이름과 같은 서버는 계속 x-mcp-{alias}-*를 자체 자격 증명으로 받아요. 서버를 소속되지 않은 접근 그룹의 이름으로 만들지 마세요.

그룹 레벨 인증 예시:

curl -X POST http://localhost:4000/mcp/dev_group \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -H "x-litellm-api-key: *** $LITELLM_API_KEY" \
  -H "x-mcp-dev_group-authorization: Bearer ***" \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'

클라이언트 인증 (Client authentication)

더 이상 사용하지 않는 브로드캐스트 헤더를 x-mcp-{server_alias}-{header_name}으로 바꾸세요. legacy compatibility 참고. 아래 클라이언트 예시는 스코프된 자격 증명을 사용해요.

서버별 인증으로 OpenAI Responses API로 연결

OpenAI를 직접 호출할 때 공개적으로 도달 가능한 LiteLLM MCP URL을 사용하고 게이트웨이 키와 스코프된 업스트림 헤더를 포함하세요:

curl --location 'https://api.openai.com/v1/responses' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer ***" \
--data '{
    "model": "gpt-5.6-terra",
    "tools": [
        {
            "type": "mcp",
            "server_label": "litellm",
            "server_url": "https://your-litellm-proxy.example.com/mcp",
            "require_approval": "never",
            "headers": {
                "x-litellm-api-key": "Bearer YOUR_LITELLM_API_KEY",
                "x-mcp-github-authorization": "Bearer YOUR_GITHUB_TOKEN",
                "x-mcp-zapier-x-api-key": "YOUR_ZAPIER_API_KEY"
            }
        }
    ],
    "input": "Run available tools",
    "tool_choice": "required"
}'

서버별 인증으로 LiteLLM Proxy Responses API로 연결

/v1/responses 엔드포인트에 대한 LLM API 요청에 LiteLLM Proxy를 호출할 때 서버별 인증과 함께 사용:

curl --location '<your-litellm-proxy-base-url>/v1/responses' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer ***" \
--data '{
    "model": "gpt-5.6-terra",
    "tools": [
        {
            "type": "mcp",
            "server_label": "litellm",
            "server_url": "litellm_proxy",
            "require_approval": "never",
            "headers": {
                "x-litellm-api-key": "Bearer YOUR_LITELLM_API_KEY",
                "x-mcp-github-authorization": "Bearer YOUR_GITHUB_TOKEN",
                "x-mcp-zapier-x-api-key": "YOUR_ZAPIER_API_KEY"
            }
        }
    ],
    "input": "Run available tools",
    "tool_choice": "required"
}'

서버별 인증으로 Cursor IDE로 연결

LiteLLM MCP로 Cursor IDE에서 직접 도구를 사용하고 서버별 인증을 포함:

설정 지침:

  1. Cursor Settings 열기: ⇧+⌘+J(Mac) 또는 Ctrl+Shift+J(Windows/Linux)
  2. MCP Tools로 이동: "MCP Tools" 탭과 "New MCP Server" 클릭
  3. 구성 추가: 아래 JSON 구성 복사·붙여넣은 후 Cmd+S 또는 Ctrl+S로 저장
{
  "mcpServers": {
    "LiteLLM": {
      "url": "http://localhost:4000/mcp/",
      "headers": {
        "x-litellm-api-key": "Bearer sk-<your-litellm-api-key>",
        "x-mcp-github-authorization": "Bearer $GITHUB_TOKEN",
        "x-mcp-zapier-x-api-key": "$ZAPIER_API_KEY"
      }
    }
  }
}

서버별 인증으로 Streamable HTTP 전송으로 연결

HTTP 전송으로 서버별 인증과 함께 LiteLLM MCP에 연결:

서버 URL:

http://localhost:4000/mcp/

헤더 (Headers):

x-litellm-api-key: *** YOUR_LITELLM_API_KEY
x-mcp-github-authorization: Bearer ***
x-mcp-zapier-x-api-key: YOUR_Z..._KEY

서버별 인증으로 Python FastMCP 클라이언트로 연결

Python FastMCP 클라이언트로 서버별 인증과 함께 LiteLLM MCP 서버에 연결:

import asyncio
import json

from fastmcp import Client
from fastmcp.client.transports import StreamableHttpTransport

# Create the transport with your LiteLLM MCP server URL and server-specific auth headers
server_url = "http://localhost:4000/mcp/"
transport = StreamableHttpTransport(
    server_url,
    headers={
        "x-litellm-api-key": "Bearer YOUR_LITELLM_API_KEY",
        "x-mcp-github-authorization": "Bearer YOUR_GITHUB_TOKEN",
        "x-mcp-zapier-x-api-key": "YOUR_ZAPIER_API_KEY"
    }
)

# Initialize the client with the transport
client = Client(transport=transport)


async def main():
    # Connection is established here
    print("Connecting to LiteLLM MCP server with server-specific authentication...")
    async with client:
        print(f"Client connected: {client.is_connected()}")

        # Make MCP calls within the context
        print("Fetching available tools...")
        tools = await client.list_tools()

        print(f"Available tools: {json.dumps([t.name for t in tools], indent=2)}")
        
        # Example: Call a tool (replace 'tool_name' with an actual tool name)
        if tools:
            tool_name = tools[0].name
            print(f"Calling tool: {tool_name}")
            
            # Call the tool with appropriate arguments
            result = await client.call_tool(tool_name, arguments={})
            print(f"Tool result: {result}")


# Run the example
if __name__ == "__main__":
    asyncio.run(main())

MCP 인증 헤더 이름 커스터마이징 (Customize the MCP Auth Header Name)

기존 배포는 더 이상 사용하지 않는 브로드캐스트 헤더를 이름 바꿀 수 있어요. central legacy header reference 참고. 새 구성은 서버별 헤더를 사용해야 해요.

/chat/completions로 MCP 도구 사용 (Use MCP tools with /chat/completions)

모든 프로바이더에서 작동 — 이 흐름은 프로바이더 비종속적이에요. 같은 MCP 도구 정의가 LiteLLM 뒤의 모든 LLM 백엔드(OpenAI, Azure OpenAI, Anthropic, Amazon Bedrock, Vertex, 자체 호스팅 배포 등)에서 작동해요.

LiteLLM Proxy는 클래식 /v1/chat/completions 엔드포인트에서도 MCP 인식 도구를 지원해요. tools 배열에 MCP 도구 정의를 직접 제공하면 LiteLLM이 MCP 서버의 도구를 가져와 OpenAI 호환 함수 호출로 변환해요. require_approval"never"로 설정되면 프록시가 반환된 도구 호출을 자동 실행하고 보조 응답을 반환하기 전에 결과를 모델로 다시 공급해요.

MCP 도구가 있는 Chat Completions:

curl --location '<your-litellm-proxy-base-url>/v1/chat/completions' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer ***" \
--data '{
  "model": "gpt-5.6-luna",
  "messages": [
    {"role": "user", "content": "Summarize the latest open PR."}
  ],
  "tools": [
    {
      "type": "mcp",
      "server_url": "litellm_proxy/mcp/github_mcp",
      "server_label": "github_mcp",
      "require_approval": "never"
    }
  ]
}'

require_approval을 생략하거나 "never" 이외의 값으로 설정하면 MCP 도구 호출이 검토·수동 실행을 위해 클라이언트에 반환되어 업스트림 OpenAI 동작과 일치해요.

LiteLLM Proxy - MCP Gateway 워크스루

LiteLLM은 관리자가 모든 MCP 서버를 LiteLLM에 추가할 수 있는 MCP 게이트웨이를 노출해요. LiteLLM Proxy를 MCP와 함께 사용하는 핵심 이점:

  1. 모든 MCP 도구에 고정 엔드포인트 사용
  2. 키, 팀, 사용자별 MCP 권한 관리

이 비디오는 MCP 서버를 LiteLLM Proxy에 온보딩하고, 사용하고, 접근 제어를 설정하는 방법을 보여줘요.

LiteLLM Python SDK MCP 브리지 (LiteLLM Python SDK MCP Bridge)

LiteLLM Python SDK는 MCP 브리지 역할을 해 LiteLLM이 지원하는 모든 모델과 MCP 도구를 함께 사용할 수 있게 해줘요. LiteLLM은 MCP 사용을 위해 다음 기능을 제공해요:

  • MCP 도구 목록(List): OpenAI 클라이언트가 사용 가능한 모든 MCP 도구를 볼 수 있음
    • 사용 가능한 모든 MCP 도구 나열: litellm.experimental_mcp_client.load_mcp_tools
  • MCP 도구 호출(Call): OpenAI 클라이언트가 MCP 도구를 호출할 수 있음
    • MCP 서버에서 OpenAI 도구 호출: litellm.experimental_mcp_client.call_openai_tool

1. 사용 가능한 MCP 도구 목록 (List Available MCP Tools)

이 예시에서 litellm.experimental_mcp_client.load_mcp_tools를 사용해 어떤 MCP 서버에서든 사용 가능한 모든 MCP 도구를 나열할 거예요. 이 메서드는 두 가지 방식으로 사용할 수 있어요:

  • format="mcp" — (기본) MCP 도구 반환
    • 반환: mcp.types.Tool
  • format="openai" — OpenAI API 호환 도구로 변환된 MCP 도구 반환. OpenAI 엔드포인트와 사용 가능
    • 반환: openai.types.chat.ChatCompletionToolParam

LiteLLM Python SDK:

# Create server parameters for stdio connection
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
import os
import litellm
from litellm import experimental_mcp_client


server_params = StdioServerParameters(
    command="python3",
    # Make sure to update to the full absolute path to your mcp_server.py file
    args=["./mcp_server.py"],
)

async with stdio_client(server_params) as (read, write):
    async with ClientSession(read, write) as session:
        # Initialize the connection
        await session.initialize()

        # Get tools
        tools = await experimental_mcp_client.load_mcp_tools(session=session, format="openai")
        print("MCP TOOLS: ", tools)

        messages = [{"role": "user", "content": "what's (3 + 5)"}]
        llm_response = await litellm.acompletion(
            model="gpt-5.6-terra",
            api_key=os.getenv("OPENAI_API_KEY"),
            messages=messages,
            tools=tools,
        )
        print("LLM RESPONSE: ", json.dumps(llm_response, indent=4, default=str))

OpenAI SDK + LiteLLM Proxy:

이 예시에서는 OpenAI SDK를 LiteLLM 프록시로 가리켜 MCP 도구를 호출하는 방법을 안내해요. 핵심 차이는 LLM API 요청을 위해 OpenAI SDK를 사용한다는 거예요.

# Create server parameters for stdio connection
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
import os
from openai import OpenAI
from litellm import experimental_mcp_client

server_params = StdioServerParameters(
    command="python3",
    # Make sure to update to the full absolute path to your mcp_server.py file
    args=["./mcp_server.py"],
)

async with stdio_client(server_params) as (read, write):
    async with ClientSession(read, write) as session:
        # Initialize the connection
        await session.initialize()

        # Get tools using litellm mcp client
        tools = await experimental_mcp_client.load_mcp_tools(session=session, format="openai")
        print("MCP TOOLS: ", tools)

        # Use OpenAI SDK pointed to LiteLLM proxy
        client = OpenAI(
            api_key="your-api-key",  # Your LiteLLM proxy API key
            base_url="http://localhost:4000"  # Your LiteLLM proxy URL
        )

        messages = [{"role": "user", "content": "what's (3 + 5)"}]
        llm_response = client.chat.completions.create(
            model="gpt-5.6-terra",
            messages=messages,
            tools=tools
        )
        print("LLM RESPONSE: ", llm_response)

2. MCP 도구 목록·호출 (List and Call MCP Tools)

이 예시에서 다음을 사용할 거예요:

  • litellm.experimental_mcp_client.load_mcp_tools — 어떤 MCP 서버에서든 사용 가능한 모든 MCP 도구 나열
  • litellm.experimental_mcp_client.call_openai_tool — MCP 서버에서 OpenAI 도구 호출

첫 LLM 응답이 OpenAI 도구 목록을 반환해요. LLM 응답의 첫 도구 호출을 가져와 MCP 서버에서 도구를 호출하도록 litellm.experimental_mcp_client.call_openai_tool에 전달해요.

litellm.experimental_mcp_client.call_openai_tool 작동 방식:

  • LLM 응답의 OpenAI Tool Call을 받아들임
  • OpenAI Tool Call을 MCP Tool로 변환
  • MCP 서버에서 MCP Tool 호출
  • MCP Tool 호출 결과 반환

LiteLLM Python SDK:

# Create server parameters for stdio connection
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
import os
import litellm
from litellm import experimental_mcp_client


server_params = StdioServerParameters(
    command="python3",
    # Make sure to update to the full absolute path to your mcp_server.py file
    args=["./mcp_server.py"],
)

async with stdio_client(server_params) as (read, write):
    async with ClientSession(read, write) as session:
        # Initialize the connection
        await session.initialize()

        # Get tools
        tools = await experimental_mcp_client.load_mcp_tools(session=session, format="openai")
        print("MCP TOOLS: ", tools)

        messages = [{"role": "user", "content": "what's (3 + 5)"}]
        llm_response = await litellm.acompletion(
            model="gpt-5.6-terra",
            api_key=os.getenv("OPENAI_API_KEY"),
            messages=messages,
            tools=tools,
        )
        print("LLM RESPONSE: ", json.dumps(llm_response, indent=4, default=str))

        openai_tool = llm_response["choices"][0]["message"]["tool_calls"][0]
        # Call the tool using MCP client
        call_result = await experimental_mcp_client.call_openai_tool(
            session=session,
            openai_tool=openai_tool,
        )
        print("MCP TOOL CALL RESULT: ", call_result)

        # send the tool result to the LLM
        messages.append(llm_response["choices"][0]["message"])
        messages.append(
            {
                "role": "tool",
                "content": str(call_result.content[0].text),
                "tool_call_id": openai_tool["id"],
            }
        )
        print("final messages with tool result: ", messages)
        llm_response = await litellm.acompletion(
            model="gpt-5.6-terra",
            api_key=os.getenv("OPENAI_API_KEY"),
            messages=messages,
            tools=tools,
        )
        print(
            "FINAL LLM RESPONSE: ", json.dumps(llm_response, indent=4, default=str)
        )

OpenAI SDK + LiteLLM Proxy:

이 예시에서는 OpenAI SDK를 LiteLLM 프록시로 가리켜 MCP 도구를 호출하는 방법을 안내해요. 핵심 차이는 LLM API 요청을 위해 OpenAI SDK를 사용한다는 거예요.

# Create server parameters for stdio connection
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
import os
from openai import OpenAI
from litellm import experimental_mcp_client

server_params = StdioServerParameters(
    command="python3",
    # Make sure to update to the full absolute path to your mcp_server.py file
    args=["./mcp_server.py"],
)

async with stdio_client(server_params) as (read, write):
    async with ClientSession(read, write) as session:
        # Initialize the connection
        await session.initialize()

        # Get tools using litellm mcp client
        tools = await experimental_mcp_client.load_mcp_tools(session=session, format="openai")
        print("MCP TOOLS: ", tools)

        # Use OpenAI SDK pointed to LiteLLM proxy
        client = OpenAI(
            api_key="your-api-key",  # Your LiteLLM proxy API key
            base_url="http://localhost:4000"  # Your LiteLLM proxy URL
        )

        messages = [{"role": "user", "content": "what's (3 + 5)"}]
        llm_response = client.chat.completions.create(
            model="gpt-5.6-terra",
            messages=messages,
            tools=tools
        )
        print("LLM RESPONSE: ", llm_response)

        # Get the first tool call
        tool_call = llm_response.choices[0].message.tool_calls[0]
        
        # Call the tool using MCP client
        call_result = await experimental_mcp_client.call_openai_tool(
            session=session,
            openai_tool=tool_call.model_dump(),
        )
        print("MCP TOOL CALL RESULT: ", call_result)

        # Send the tool result back to the LLM
        messages.append(llm_response.choices[0].message.model_dump())
        messages.append({
            "role": "tool",
            "content": str(call_result.content[0].text),
            "tool_call_id": tool_call.id,
        })

        final_response = client.chat.completions.create(
            model="gpt-5.6-terra",
            messages=messages,
            tools=tools
        )
        print("FINAL RESPONSE: ", final_response)

FAQ

Q: LiteLLM 뒤의 MCP 서버에서 OAuth2 client_credentials(machine-to-machine)를 어떻게 사용하나요?

LiteLLM은 client_credentials 그랜트에 대한 자동 토큰 관리를 지원해요. MCP 서버에 client_id, client_secret, token_url을 구성하면 LiteLLM이 토큰을 자동으로 가져오고·캐시하고·새로고침해요. 설정 지침은 MCP OAuth M2M 가이드 참고.

Q: LiteLLM UI에서 OAuth 토큰을 가져오면 어디에 저장되나요?

UI는 OAuth 리다이렉트 흐름을 끝낼 수 있도록 sessionStorage에 일시 상태만 유지하며, 토큰은 서버나 데이터베이스에 저장되지 않아요.

Q: MCP 연결 오류가 보여요. 무엇을 확인해야 하나요?

MCP Troubleshooting Guide의 5분 분류부터 시작하세요. 하나의 curl이 실패 레이어(클라이언트 → LiteLLM vs. LiteLLM → MCP)를 격리하고, 증상 매트릭스가 각 상태 코드·증상을 수정에 매핑해요. 에스컬레이션이 필요하면 먼저 support bundle을 수집하세요.

더 알아보기 (Learn more)