MCP Server Auth Template

io.github.brunovicco由 GitHub 帳號 brunovicco 發布v0.7.0更新於 Oct 24, 2026

OAuth 2.1/OIDC resource-server reference for secure MCP authorization

概覽

AI 產生的概覽

一個參考用的 OAuth 2.1/OIDC 資源伺服器,在嚴格權杖驗證與依主體授權之後才暴露 MCP 工具。

可以做什麼
這是一套面向正式環境的 MCP 資源伺服器參考實作,在派送工具之前先驗證 OAuth 2.1/OIDC 存取權杖。它會發佈 RFC 9728 受保護資源中繼資料,透過 RFC 8707 將權杖綁定到精確的對象,並在簽發者、簽章、到期時間、演算法與呼叫方類型檢查上採取失敗即拒絕的策略。它提供 whoami、health 等範例工具,依主體過濾 tools/list,並在需要提升權限時回傳 403 insufficient_scope。它支援 Microsoft Entra ID 與通用 OIDC 轉接器,並輸出僅含中繼資料的 OpenTelemetry 追蹤。
適用情境
當難點不在於如何暴露 MCP 工具,而在於如何在不削弱身分、授權、傳輸與可觀測性邊界的前提下暴露它時,適合使用。它適合需要 Entra ID 或通用 OIDC 資源伺服器行為可用參考的團隊,也適合希望端對端驗證權杖驗證、作用域挑戰與無狀態 MCP 行為的團隊。
執行需求
以本機行程或容器方式執行。從原始碼執行需要 Python 3.13 或 3.14 以及 uv;已發佈的 OCI 映像透過 Docker 以 streamable-http 執行。必要的環境變數包括 MCP_SERVER_AUTH_PROVIDER 與 MCP_SERVER_RESOURCE_SERVER_URL;entra 設定還需要 MCP_SERVER_ENTRA_APPLICATION_ID_URI、MCP_SERVER_ENTRA_AUDIENCE 與 MCP_SERVER_ENTRA_TENANT_ID,generic 設定需要 MCP_SERVER_GENERIC_AUDIENCE 與 MCP_SERVER_GENERIC_ISSUER_URL。還需要一個 OIDC 授權伺服器,並能存取其探索與 JWKS 端點。
安裝前請注意
這是一套透明的參考範本,不是安全認證,也不是代管身分服務。實際部署仍需自行提供 TLS 終止、密鑰遞送、供應商註冊、網路原則、容量規劃以及真實 IdP 驗證。儲存庫中已提交的 .invalid 與全零值都是佔位符,會在正式環境預檢時失敗。Bearer 權杖與解碼後的宣告僅保留在請求內,不會寫入日誌或追蹤,但追蹤功能可被啟用並匯出到 OTLP 端點,因此在調整邊界前應查閱隱私與資料處理文件。

安裝

在 SourceWeft 中

  1. 開啟 儀表板中的 MCP Server Auth Template,將其新增到工作區。
  2. 為需要使用其工具的對話啟用該服務。

Desktop only,透過 STDIO。 STDIO 服務會啟動本機處理程序,因此需要 SourceWeft 桌面主機。

其他 MCP 客戶端

參照 儲存庫 中的啟動說明。

README

mcp-server-auth-template

[quality] [compatibility] [release] [python] [license]

Leia em português

A production-oriented OAuth 2.1 resource-server reference for remote MCP: Microsoft Entra ID and generic OIDC, exact token/resource validation, fail-closed authorization, progressive scope challenges, stateless MCP 2026-07-28, and metadata-only OpenTelemetry evidence.

Use this repository when the hard part is not "how do I expose an MCP tool?" but how do I expose it without weakening identity, authorization, transport, and observability boundaries. The server pairs with mcp-client-auth-template for an executable end-to-end reference using synthetic identities and no production credentials.

What this repository proves

The paired executable path validates real resource-server behavior rather than configuration claims:

  • ✅ RFC 9728 Protected Resource Metadata is published by the resource server
  • ✅ RFC 8707 resource binding becomes an exact JWT audience boundary
  • ✅ issuer, signature, expiry, algorithm/key compatibility and caller type fail closed
  • ✅ delegated scopes and Entra application roles remain distinct authorization concepts
  • ✅ 403 insufficient_scope is returned before dispatch for progressive authorization
  • ✅ wrong-audience tokens are rejected with 401, with an explicit token-resource policy that does not depend on MCP SDK defaults
  • ✅ tools/list is filtered per principal and carries only bounded private cache hints
  • ✅ protected tools stay hidden from anonymous catalog discovery
  • ✅ MCP 2026-07-28 stays stateless and does not mint Mcp-Session-Id
  • ✅ generic OIDC and Microsoft Entra ID share one application boundary without provider leakage
  • ✅ W3C trace context reaches the server while OAuth/MCP sensitive values stay out of telemetry
  • ✅ release artifacts, container evidence, SBOMs and provenance are validated by executable gates

For a requirement-by-requirement view of the paired OAuth/MCP behavior, including explicit evidence gaps and discussion topics for the MCP Authorization Interest Group / Tool Scopes Working Group, see the Authorization Implementer Report.

Architecture

mermaid
flowchart LR    Client["MCP client"] -->|"OAuth 2.1 / OIDC"| AS["Authorization server<br/>Entra ID or generic OIDC"]    Client -->|"MCP 2026-07-28<br/>resource-bound bearer"| Admission["Transport admission"]    Admission --> AuthN["Token verification"]    AuthN --> AuthZ["Tool authorization"]    AuthZ --> Tools["MCP tools"]    Server["This resource server"] --- Admission
    Server -->|"OIDC discovery + cached JWKS"| AS    Server -.->|"W3C trace context + OTLP"| Collector["OpenTelemetry Collector"]    Collector --> Tempo["Tempo"]    Tempo --> Grafana["Grafana"]

The authorization server owns login, consent, client registration and token issuance. This repository owns the protected resource: transport admission, metadata publication, access-token verification, request-scoped principal construction, tool authorization and dispatch.

For layer boundaries and the detailed authorization sequence, see Architecture.

5-minute verification

The companion client owns the executable cross-repository reference flow. With both repositories cloned as siblings, verify this server directly from source:

bash
cd ../mcp-client-auth-template./scripts/run_reference_demo.sh \  --server-root ../mcp-server-auth-template

The flow starts the real server from this checkout plus a deterministic local OIDC provider and proves CIMD-first Authorization Code + PKCE, authenticated whoami, bounded scope step-up, wrong-audience rejection and stateless MCP behavior.

For the observable published-image proof:

bash
cd ../mcp-client-auth-template./scripts/run_observability_demo.sh --keep

The observable flow verifies one distributed trace across client and server, positive Collector receipt, Tempo retrieval, Grafana provisioning and telemetry privacy assertions.

See Verification guide for the exact evidence boundary.

Visual proof

The terminal proof below is captured from the source-level paired reference flow:

[Server reference demo]

The trace screenshots are captured from a successful observable run and focus on mcp-server-auth-template spans:

[Server distributed trace]

[Server distributed trace detail]

Authentication profiles

ProfileIntended useKey behavior
Entra delegatedInteractive enterprise usersValidates scp, tenant/application identifiers, issuer, audience and subject
Entra applicationProvider-specific app-only deploymentsRequires explicit idtyp=app; keeps roles separate from delegated scopes
Generic OIDC delegatedStandards-based interactive clientsValidates issuer/audience/signature/expiry and OAuth scopes
Generic OIDC client credentialsUnattended services in the deterministic pair profileAccepts pre-registered machine tokens and progressive OAuth scopes

Set MCP_SERVER_AUTH_PROVIDER=entra or generic to switch adapters. The example whoami tool returns the verified caller identity; health requires the additional mcp:tools:health scope and demonstrates a pre-dispatch 403 insufficient_scope challenge.

Quick start

Prerequisites: Python 3.13 or 3.14 and uv.

bash
git clone https://github.com/brunovicco/mcp-server-auth-template.gitcd mcp-server-auth-templatecp .env.example .envuv sync --frozen --all-groupsuv run uvicorn mcp_server_auth_template.entrypoints.mcp_server:create_app --factory --reload

Configure either the Entra or generic-OIDC block in .env, then point an MCP client at http://localhost:8000/mcp.

EndpointPurposeAuthentication
/mcpMCP Streamable HTTPBearer token
/.well-known/oauth-protected-resourceAuthorization-server discovery metadataPublic
/livezProcess livenessPublic, minimal response
/readyzMCP lifespan readinessPublic, minimal response

For production-style execution:

bash
uv run python -m mcp_server_auth_template.entrypoints.serve

See Production operations before exposing the service outside loopback.

Official MCP Registry

The server is published in the Official MCP Registry as:

io.github.brunovicco/[email protected]

server.json describes the public GHCR image as an OCI package using the real streamable-http transport; it does not claim a hosted remotes endpoint. Publication is gated by the secure release pipeline and a dedicated Registry workflow that validates the immutable image, ownership metadata, and persisted Registry responses before publication.

See Official MCP Registry and the Authorization Implementer Report.

Security properties

The implementation is deliberately fail closed:

  • exact issuer and audience validation, bounded clock checks, algorithm/key compatibility and cached JWKS refresh;
  • an explicit validate_token_resource=False policy: provider audiences (Entra API client ID, api:// identifiers) are enforced by the token verifier, never by SDK URL string equality (ADR-0027);
  • principal-dependent discovery results are never shareable across authorization contexts (ADR-0028);
  • hardened discovery/JWKS egress against unsafe schemes, redirects, compression, oversized bodies, private/reserved destinations, mixed DNS answers and DNS rebinding;
  • Host, Origin, header, envelope, body-size and concurrency admission before authentication and tool dispatch;
  • delegated and application identities remain distinct; extension negotiation never grants authorization by itself;
  • bearer tokens and decoded claims remain request-local and are never logged or persisted;
  • tracing excludes credentials, arbitrary headers and URLs, MCP arguments/results, bodies, baggage and exception text.

This is a transparent reference implementation, not a security certification. Read Privacy and data handling and the architecture decisions under docs/adr/ before adapting the boundary.

MCP 2026-07-28

Baseline: MCP specification 2026-07-28 and MCP Python SDK >=2.2,<3.

The paired templates exercise the modern stateless profile as executable behavior:

  • server/discover and per-request _meta carry protocol version, client identity and capabilities without the legacy initialize / initialized handshake;
  • modern requests use MCP-Protocol-Version, Mcp-Method and Mcp-Name;
  • responses do not mint Mcp-Session-Id;
  • Protected Resource Metadata drives authorization-server discovery;
  • RFC 8707 resource binds the access token audience exactly;
  • server/discover and tools/list carry SEP-2549 cache hints (ttlMs=30000, cacheScope=private);
  • runtime 403 insufficient_scope preserves prior grants and permits only one bounded replay of the undispatched operation;
  • machine-to-machine access is opt-in through io.modelcontextprotocol/oauth-client-credentials.

See Compatibility and the companion client's cross-repository E2E evidence.

Observability

a2a-otel-kit continues W3C trace context at the MCP ASGI boundary. Export remains network-silent unless A2A_OTEL_ENABLED=true and a complete OTLP traces endpoint are configured. Spans are metadata-only and sit inside hardened HTTP admission but outside authentication and tool dispatch.

See LLM and application observability.

Engineering evidence

  • deterministic quality gate covering lint, format, strict Mypy, architecture, tests/coverage, Bandit, dependency audit, supply-chain controls, governance and vendored contract validation;
  • SHA-pinned GitHub Actions with read-only permissions by default and isolated release authorities;
  • CycloneDX source/runtime inventories, complete vulnerability evidence and fail-closed exception policy;
  • allowlisted byte-reproducible Python release artifacts with SHA-256 manifests and GitHub build provenance;
  • policy-approved GHCR publication with immutable digest, provenance and SBOM attestations;
  • Python 3.13/3.14 against MCP SDK 2.2.0 and latest compatible 2.x, with MCP SDK deprecation warnings promoted to test failures so MCP 3 breakage surfaces early;
  • offline JWT fixtures using local keys and synthetic identities;
  • ADRs documenting security, protocol, operations, compatibility, observability and supply-chain decisions.

Demo vs production

Reference evidenceProduction adoption
Synthetic local OIDC in companion demoEnterprise authorization server with reviewed registration and consent
Loopback/local reference networkingTLS-protected service networking and explicit proxy ownership
Local Collector/Tempo/GrafanaOrganization-managed telemetry pipeline and retention policy
Synthetic signing keys and identitiesManaged keys, secrets and provider-specific controls
Reference whoami / health toolsDomain tools with explicit authorization policies and side-effect controls

The reference settings prove boundaries; they are not production defaults.

Repository structure

text
src/                    resource-server implementationtests/                  unit, contract and security evidencescripts/                quality, governance and release automationdocs/                   architecture, operations, privacy and securityexamples/                deployment/reference configuration.github/workflows/      CI, compatibility and release workflows

Local editor and coding-agent state is intentionally excluded from the public repository.

Documentation

DocumentUse it for
VerificationSource-level and observable paired proof
ArchitectureContext, layers, dependency rules and request sequence
CompatibilitySupported versions and executable client/server contract
OperationsPreflight, probes, shutdown, containers and Kubernetes
PrivacyData inventory, retention, logging, tracing and external processors
Supply chainDependency policy, CI trust boundary, threats and exceptions
ObservabilityOpenTelemetry and optional Langfuse configuration
DevelopmentLocal environment, checks and container workflow
Architecture decisionsRationale and trade-offs behind material decisions

Testing and quality

bash
uv lock --checkuv sync --frozen --all-groupsuv run pytestuv run python scripts/quality_gate.py

The quality gate is the definition of done. It covers lint, format, architecture, strict typing, tests/coverage, Bandit, dependency audit, supply-chain controls, governance and vendored contract validation.

Scope and production adoption

This repository is a reference template, not a hosted identity service. A concrete deployment must still provide TLS termination, immutable image publishing, secret delivery, provider-specific registration, network policy, capacity planning, monitoring ownership and live IdP validation. Checked-in .invalid and all-zero values are placeholders and fail production preflight.

License

MIT

來源:README.md,提交 8b1d6d9

工具

0
SourceWeft 尚未在沙箱中啟動過該軟體包,因此其工具未知。

版本歷史

2
  1. v0.7.0最新Sep 23, 2026
  2. v0.6.2Sep 16, 2026

評分

已滿足適用檢查項的 50%

該評分衡量此收錄條目的完整程度,依據註冊中心條目、端點與公開來源計算得出。它不是對伺服器本身的評價,也不表示伺服器安全或目前可用:可連通性是帶日期的檢查結果,評分也不包含安裝量或使用者評價。

  • 近 30 天內可連通25 分

    請保持端點能夠回應 MCP 握手;SourceWeft 每 30 天探測一次。

  • 已宣告認證方式10 分

    請在註冊中心條目中宣告憑證請求標頭,或保持端點能夠回應探測,以便判定其認證方式。

  • 已列出工具15 分

    請讓伺服器在無憑證時回應 tools/list,或發布可在沙箱中無憑證啟動的軟體包。

  • 描述必需15 分
  • 圖示10 分
  • 文件15 分
  • 授權條款10 分