Build with Portmii.

Add paid access to your MCP tools. Check customers, reserve usage and record the result through a small HTTP API.

This reference covers the Runtime API and TypeScript SDK. Product setup, customer accounts and billing use separate creator and customer APIs. OAuth discovery and token exchange run through Portmii’s authorization server.

Runtime v1JSON over HTTPSServer to server
API origin
https://api.portmii.com

Use the origin of your MCP-enabled deployment.

GET/v1/mcp/runtime/health

Two keys. Clear roles.

Your server authenticates with a provider runtime key. The JSON body identifies the customer whose access you want to check.

First configure an active provider, product and registered tool. Enable runtime access and the creator’s MCP entitlement. The customer needs an active grant and usage period.

Provider runtime key

Authorization: Bearer pmcp_sk_…

Secret, product-bound and server-only. A customer key or creator login token cannot replace it.

Customer credential

customerCredential: pmcp_ck_…

Read it from the incoming request. For OAuth, send accessToken instead. Supply exactly one credential field.

One tool call, start to finish.

Start with reserve
01

Reserve

Check access and hold the configured usage cost.

02

Run your tool

Your server executes the handler within the five-minute lease.

03

Confirm the outcome

Commit after success. Release if execution fails.

Before you copy a request

Run examples on your server. Set PORTMII_API_URL to your API origin without a trailing slash or path. Set PORTMII_PROVIDER_KEY and PORTMII_CUSTOMER_KEY from your configuration and the incoming customer request.

Generate a unique UUID for each invocation and keep it as PORTMII_REQUEST_KEY. Reuse that key for reserve, commit or release, and retries. Set PORTMII_RESERVATION_ID from the reservation response before a terminal request. Persist both values if you need crash recovery.

Examples use your registered reports.generate tool. cURL runs in Bash and uses jq to encode customer credentials. JavaScript requires Node.js 20+; Python uses its standard library; PHP requires cURL. Each snippet makes one request and prints the response.

Deployment availability

This contract was checked against the MCP backend on 2 October 2026. Confirm health returns {"status":"ok"} in your target environment. Health reports dependency readiness; an authenticated reserve or access check also requires product access, runtime enablement and the creator’s MCP entitlement.

Reserve a tool call

#
POST/v1/mcp/runtime/usage/reservationsAuthenticated

Authenticate the customer, check access, and atomically reserve the configured tool cost. Execute your tool only after a live RESERVED response.

Authorizationheader · required

Bearer token containing your product's provider runtime key.

Idempotency-Keyheader · required

1–255 characters, without CR/LF. One server-generated key per invocation, reused throughout its lifecycle.

toolbody · string · required

Exact registered tool name, 1–255 characters. Portmii calculates its cost and limits.

customerCredentialbody · string

Customer API key: pmcp_ck_ followed by 22 base64url characters, a dot, and 43 base64url characters. Omit when using OAuth.

OAuth & optional fields
accessTokenbody · string

Customer OAuth token, 1–8,192 characters. Send this instead of customerCredential. The product’s authMode must be OAUTH or API_KEY_AND_OAUTH; keys require API_KEY or API_KEY_AND_OAUTH.

assertedResourcebody · string · optional

Up to 2,048 characters. Must exactly match the configured MCP server URL, including its path and trailing slash.

Unknown fields are rejected. Do not send customer IDs, tenant IDs, tool arguments, usage quantities or null credential placeholders.

Before execution, check status: "RESERVED" and a future expiresAt. A replay may already be committed, released or expired.

Reserve a tool call request
# Create and persist one request key per invocation. Reuse it on retries.
set +x # Do not trace credential-bearing shell expansions.
set -euo pipefail
: "${PORTMII_API_URL:?Set PORTMII_API_URL}"
: "${PORTMII_PROVIDER_KEY:?Set PORTMII_PROVIDER_KEY}"
: "${PORTMII_CUSTOMER_KEY:?Set PORTMII_CUSTOMER_KEY}"
: "${PORTMII_REQUEST_KEY:?Set PORTMII_REQUEST_KEY}"

config=$(printf '%s\0' "$PORTMII_PROVIDER_KEY" "$PORTMII_CUSTOMER_KEY" "$PORTMII_REQUEST_KEY" | jq -Rrs '
  def header: if test("[\u0000-\u001f\u007f]") then error("Invalid header control character") else @json end;
  split("\u0000") as [$PORTMII_PROVIDER_KEY, $PORTMII_CUSTOMER_KEY, $PORTMII_REQUEST_KEY] |
  "header = " + ("Authorization: Bearer " + $PORTMII_PROVIDER_KEY | header),
  "header = " + ("Idempotency-Key: " + $PORTMII_REQUEST_KEY | header),
  "header = " + ("Content-Type: application/json" | header),
  "data-binary = " + ({"customerCredential":$PORTMII_CUSTOMER_KEY,"tool":"reports.generate"} | tojson | @json)
')

printf '%s\n' "$config" | curl -q --config - --fail-with-body --silent --show-error \
  --request POST \
  "$PORTMII_API_URL/v1/mcp/runtime/usage/reservations"
200 OKExample response
Reserve a tool call response
{
  "reservationId": "153b9e60-6b9b-46ef-973c-2c065e1c7e95",
  "status": "RESERVED",
  "cost": 1,
  "reserved": 1,
  "remaining": 99,
  "expiresAt": "2026-10-02T12:05:00Z",
  "outcome": null
}

Commit successful usage

#
POST/v1/mcp/runtime/usage/reservations/{reservationId}/commitAuthenticated

After the tool succeeds, convert its reservation into consumed usage. Return the result only after a matching COMMITTED acknowledgment.

reservationIdpath · UUID · required

The ID returned by reserve. Use the original request key for this reservation.

Authorizationheader · required

Bearer token containing your product's provider runtime key.

Idempotency-Keyheader · required

1–255 characters, without CR/LF. One server-generated key per invocation, reused throughout its lifecycle.

No request body is required. Return your tool's result only after the matching COMMITTED acknowledgment.

Commit and release still require a valid provider key bound to this product. Existing reservations can be settled after a provider or product becomes inactive or new runtime access is disabled. Reservations already marked EXPIRED cannot be committed or released.

Commit successful usage request
# Reuse the reservation ID and request key from reserve.
set +x # Do not trace credential-bearing shell expansions.
set -euo pipefail
: "${PORTMII_API_URL:?Set PORTMII_API_URL}"
: "${PORTMII_PROVIDER_KEY:?Set PORTMII_PROVIDER_KEY}"
: "${PORTMII_REQUEST_KEY:?Set PORTMII_REQUEST_KEY}"
: "${PORTMII_RESERVATION_ID:?Set PORTMII_RESERVATION_ID}"

config=$(printf '%s\0' "$PORTMII_PROVIDER_KEY" "$PORTMII_REQUEST_KEY" | jq -Rrs '
  def header: if test("[\u0000-\u001f\u007f]") then error("Invalid header control character") else @json end;
  split("\u0000") as [$PORTMII_PROVIDER_KEY, $PORTMII_REQUEST_KEY] |
  "header = " + ("Authorization: Bearer " + $PORTMII_PROVIDER_KEY | header),
  "header = " + ("Idempotency-Key: " + $PORTMII_REQUEST_KEY | header)
')

printf '%s\n' "$config" | curl -q --config - --fail-with-body --silent --show-error \
  --request POST \
  "$PORTMII_API_URL/v1/mcp/runtime/usage/reservations/$PORTMII_RESERVATION_ID/commit"
200 OKExample response
Commit successful usage response
{
  "reservationId": "153b9e60-6b9b-46ef-973c-2c065e1c7e95",
  "status": "COMMITTED",
  "cost": 1,
  "reserved": 0,
  "remaining": 99,
  "expiresAt": "2026-10-02T12:05:00Z",
  "outcome": null
}

Release a failed call

#
POST/v1/mcp/runtime/usage/reservations/{reservationId}/releaseAuthenticated

Release a reservation when tool execution fails. Send a stable outcome code, never raw exception text or tool input.

reservationIdpath · UUID · required

The ID returned by reserve. Use the original request key for this reservation.

Authorizationheader · required

Bearer token containing your product's provider runtime key.

Idempotency-Keyheader · required

1–255 characters, without CR/LF. One server-generated key per invocation, reused throughout its lifecycle.

outcomebody · enum · required

A stable failure category:

tool_errortimeoutcanceleddependency_errorvalidation_error

Keep the same outcome when retrying. Do not send raw exception text or tool input.

Commit and release still require a valid provider key bound to this product. Existing reservations can be settled after a provider or product becomes inactive or new runtime access is disabled. Reservations already marked EXPIRED cannot be committed or released.

Release only when tool execution failed. After a successful tool call and a commit timeout, retry commit with the original key.

Release a failed call request
# Reuse the reservation ID and request key from reserve.
set +x # Do not trace credential-bearing shell expansions.
set -euo pipefail
: "${PORTMII_API_URL:?Set PORTMII_API_URL}"
: "${PORTMII_PROVIDER_KEY:?Set PORTMII_PROVIDER_KEY}"
: "${PORTMII_REQUEST_KEY:?Set PORTMII_REQUEST_KEY}"
: "${PORTMII_RESERVATION_ID:?Set PORTMII_RESERVATION_ID}"

config=$(printf '%s\0' "$PORTMII_PROVIDER_KEY" "$PORTMII_REQUEST_KEY" | jq -Rrs '
  def header: if test("[\u0000-\u001f\u007f]") then error("Invalid header control character") else @json end;
  split("\u0000") as [$PORTMII_PROVIDER_KEY, $PORTMII_REQUEST_KEY] |
  "header = " + ("Authorization: Bearer " + $PORTMII_PROVIDER_KEY | header),
  "header = " + ("Idempotency-Key: " + $PORTMII_REQUEST_KEY | header),
  "header = " + ("Content-Type: application/json" | header),
  "data-binary = " + ({"outcome":"tool_error"} | tojson | @json)
')

printf '%s\n' "$config" | curl -q --config - --fail-with-body --silent --show-error \
  --request POST \
  "$PORTMII_API_URL/v1/mcp/runtime/usage/reservations/$PORTMII_RESERVATION_ID/release"
200 OKExample response
Release a failed call response
{
  "reservationId": "153b9e60-6b9b-46ef-973c-2c065e1c7e95",
  "status": "RELEASED",
  "cost": 1,
  "reserved": 0,
  "remaining": 100,
  "expiresAt": "2026-10-02T12:05:00Z",
  "outcome": "tool_error"
}

Check access without metering

#
POST/v1/mcp/runtime/access/verifyAuthenticated

Optional access precheck. HTTP 200 can contain allowed: false. This endpoint neither reserves nor consumes usage; reserve still performs the authoritative check.

Authorizationheader · required

Bearer token containing your product's provider runtime key.

toolbody · string · required

Exact registered tool name, 1–255 characters. Portmii calculates its cost and limits.

customerCredentialbody · string

Customer API key: pmcp_ck_ followed by 22 base64url characters, a dot, and 43 base64url characters. Omit when using OAuth.

OAuth & optional fields
accessTokenbody · string

Customer OAuth token, 1–8,192 characters. Send this instead of customerCredential. The product’s authMode must be OAUTH or API_KEY_AND_OAUTH; keys require API_KEY or API_KEY_AND_OAUTH.

assertedResourcebody · string · optional

Up to 2,048 characters. Must exactly match the configured MCP server URL, including its path and trailing slash.

Unknown fields are rejected. Do not send customer IDs, tenant IDs, tool arguments, usage quantities or null credential placeholders.

HTTP 200 can contain allowed: false. Check the decision body. A successful precheck does not replace a reservation.

Check access without metering request
# Inspect allowed in the response, even on HTTP 200.
set +x # Do not trace credential-bearing shell expansions.
set -euo pipefail
: "${PORTMII_API_URL:?Set PORTMII_API_URL}"
: "${PORTMII_PROVIDER_KEY:?Set PORTMII_PROVIDER_KEY}"
: "${PORTMII_CUSTOMER_KEY:?Set PORTMII_CUSTOMER_KEY}"

config=$(printf '%s\0' "$PORTMII_PROVIDER_KEY" "$PORTMII_CUSTOMER_KEY" | jq -Rrs '
  def header: if test("[\u0000-\u001f\u007f]") then error("Invalid header control character") else @json end;
  split("\u0000") as [$PORTMII_PROVIDER_KEY, $PORTMII_CUSTOMER_KEY] |
  "header = " + ("Authorization: Bearer " + $PORTMII_PROVIDER_KEY | header),
  "header = " + ("Content-Type: application/json" | header),
  "data-binary = " + ({"customerCredential":$PORTMII_CUSTOMER_KEY,"tool":"reports.generate"} | tojson | @json)
')

printf '%s\n' "$config" | curl -q --config - --fail-with-body --silent --show-error \
  --request POST \
  "$PORTMII_API_URL/v1/mcp/runtime/access/verify"
200 OKExample denied decision
Check access without metering response
{
  "allowed": false,
  "reasonCode": "grant_missing",
  "correlationId": "f731801c-32c3-4a4f-96b7-d8c0a2a1bcda",
  "subject": null,
  "plan": null,
  "entitlements": [],
  "grantVersion": null,
  "usage": null
}

Check runtime readiness

#
GET/v1/mcp/runtime/healthPublic

Unauthenticated aggregate readiness check. Returns HTTP 200 with status: ok, or HTTP 503 with status: unavailable.

HTTP 200 means ready. HTTP 503 with status: "unavailable" means the runtime cannot serve requests.

Check runtime readiness request
# Health is public. No provider key is sent.
set +x # Do not trace credential-bearing shell expansions.
set -euo pipefail
: "${PORTMII_API_URL:?Set PORTMII_API_URL}"

curl -q --fail-with-body --silent --show-error \
  --request GET \
  "$PORTMII_API_URL/v1/mcp/runtime/health"
200 OKExample response
Check runtime readiness response
{
  "status": "ok"
}

Retries without double execution.

Keep one invocation identity.

Generate your key on the server and retain the customer, tool and reservation identity. Alternative authentication headers and query-string credentials are rejected. The provider key selects the product; tenant or product IDs cannot switch that context.

Usage idempotency does not deduplicate your handler. Concurrent requests may receive the same live reservation. Store execution state or lock the handler in your server. A customer-supplied MCP request ID is not a globally unique accounting key.

Resolve an uncertain commit.

After a commit timeout, retry only commit with the original key and reservation ID, using bounded backoff. Never execute the tool again, create a new reservation, or release after success.

Finish within the five-minute lease and leave time to commit. There is no renewal endpoint. Expired or incompatible states can return reservation_conflict. An expiry job recovers abandoned reservations.

Usage values & failure handling

cost is the tool's configured usage cost. reserved is this reservation's hold, which becomes zero after commit or release. remaining is the balance at that mutation; replayed responses are not a current balance lookup. remaining: null means no customer limit, although creator limits may still apply.

Preserve the original tool error if release fails. Retry release with the same key and outcome. Persist identifiers for crash recovery, and use your own idempotency strategy for external tool side effects.

Know what to handle.

Use reasonCode for application logic and correlationId when contacting support. You can send X-Correlation-ID; Portmii normalizes it.

Invalid request bodies may also include errors: an array of field and constraint names, without submitted values.

Proxy and rate-limit errors may use a different response body. Handle non-JSON failures too. A failed reservation must never start the tool.

Error response
{
  "reasonCode": "usage_limit_exceeded",
  "correlationId": "f731801c-32c3-4a4f-96b7-d8c0a2a1bcda"
}
400Invalid request

Check JSON fields, credential choice, UUIDs, and the required Idempotency-Key. DTO validation can include errors with field and constraint names.

invalid_request
401Authentication failed

Replace or refresh the relevant credential and check the product auth mode. Invalid or expired customer OAuth tokens use invalid_customer_credential.

invalid_provider_credentialinvalid_customer_credential
403Access denied

Check product access, customer entitlements and the creator’s MCP entitlement. feature_disabled means runtime or pilot access is not enabled. Do not execute the tool.

provider_inactiveproduct_inactiveresource_mismatchcustomer_blockedgrant_missinggrant_inactivetool_inactiveentitlement_missingfeature_disabled
404Unknown tool

Use an exact tool name registered for this product.

tool_unknown
409Conflicting state

Check the original key, reservation, and state. Do not retry with a new key to bypass a conflict. For concurrent state changes, retry only the same API operation with bounded backoff.

idempotency_conflictreservation_conflictstate_conflictresource_conflict
429Usage limit reached

A customer or creator usage limit is exhausted. Wait for the relevant usage period or adjust the plan. Generic rate limiting can also return 429.

usage_limit_exceeded
503Temporarily unavailable

Do not execute without a confirmed reservation. Retry a transient API operation with bounded backoff and the same key.

usage_period_missingdependency_unavailabletemporarily_unavailable

For access/verify, customer and policy denials can arrive as HTTP 200 with allowed: false. Invalid provider credentials and dependency failures still use non-2xx responses.

One middleware. One wrapper per tool.

SDK source & README

Install @portmii/mcp in your Node.js 20.19+ or 22.12+ server. Create one client, mount portmii.auth before the MCP HTTP route, and pass portmii.tool(name, handler) to registerTool. Use your existing Node/Express app, MCP server and Zod input schema. Register the same tool name in Portmii.

Install the TypeScript SDK
npm install @portmii/mcp
TypeScript handler integration
import { createPortmii } from '@portmii/mcp';
import { z } from 'zod/v4';

// Reads PORTMII_PROVIDER_KEY from the environment.
const portmii = createPortmii({
  authType: 'OAUTH', // or 'API_KEY' | 'OAUTH_OR_API_KEY'
  serverUrl: 'https://provider.example/mcp',
  onUnavailable: 'deny', // or 'allow': run tools while Portmii cannot answer
});

// Mount before your MCP HTTP route.
app.use(portmii.auth);

mcp.registerTool(
  'echo',
  { inputSchema: z.object({ message: z.string() }) },
  portmii.tool('echo', ({ message }) => ({
    content: [{ type: 'text', text: message }],
  })),
);

Match your product configuration.

authTyperequired

SDK OAUTH matches product OAUTH; API_KEY matches API_KEY; OAUTH_OR_API_KEY matches API_KEY_AND_OAUTH. Customers send exactly one credential per call.

providerKeyrequired · defaults to env

Your product-bound pmcp_sk_… key. Defaults to PORTMII_PROVIDER_KEY. Keep it in server configuration.

serverUrlrequired for OAUTH / OAUTH_OR_API_KEY

Your public HTTPS MCP endpoint, matching the product’s configured URL. Used for OAuth discovery and token audience. For API_KEY without a URL, mount only on the MCP route: app.use('/mcp', portmii.auth).

onUnavailablerequired · no default

'deny' or 'allow'. Decides whether tools run while Portmii cannot answer: network error, timeout, 5xx, feature_disabled or dependency_unavailable. Applies after retries. A missing or invalid value throws INVALID_CONFIG.

authorizeoptional · default deny

Called with { toolName, reasonCode, grant } when Portmii denies a call. Return 'allow' to run the tool anyway. grant holds the subscription facts Portmii sent (source, planId, validTo), when present. Never called when Portmii cannot answer.

onUnmeteredoptional

Called with { toolName, reason } right before a tool runs without a reservation. reason is 'unavailable' or 'authorized'. It is awaited; if it throws, the tool does not run.

baseUrloptional

Defaults to PORTMII_BASE_URL or https://api.portmii.com. Its origin is the OAuth issuer. URLs require HTTPS; HTTP is allowed for localhost, 127.0.0.1 and [::1].

timeoutMsoptional · default 30000

Timeout for each Portmii HTTP request, in milliseconds. It does not set a tool execution deadline.

Let the middleware carry identity.

For OAuth, the middleware serves /.well-known/oauth-protected-resource and its MCP-path variant. A 401 challenge directs clients to Portmii’s Authorization Code + PKCE flow. Tokens are checked against the issuer, audience, expiry and JWKS signature.

In API-key modes, customers send X-API-Key or Authorization: Bearer pmcp_ck_… to your MCP server. Send exactly one credential. The Runtime API still receives the provider key in its Authorization header and the customer credential in JSON.

The middleware sets req.auth. Official MCP SDK v1 passes it as extra.authInfo; v2 uses ctx.http.authInfo. Your handler keeps its usual (input, context) arguments. Honor context.signal in v1 or context.mcpReq.signal in v2.

Your server decides access.

Portmii provides customer login, subscription data and usage counters; its answer is input for your decision. When Portmii allows a call, usage is reserved, the tool runs and usage is committed. When Portmii denies a call, it fails with PortmiiError unless authorize returns 'allow'. When Portmii cannot answer, onUnavailable decides.

A call allowed by authorize or onUnavailable runs without a reservation, so Portmii does not bill it. Allowing an authentication failure such as invalid_customer_credential lets unknown callers run the tool. With onUnavailable: 'allow', any well-formed customer API key runs tools while Portmii is unreachable; OAuth tokens are still verified locally.

Resolved calls consume usage.

The wrapper reserves before execution, commits when the handler resolves and attempts release when it throws. Throw an error to avoid billing a failed call; returning { isError: true } still commits. Tool inputs and outputs are not sent to Portmii.

Every invocation gets a fresh internal UUID, even if the MCP request ID repeats. Finish the handler and commit within the five-minute lease. Commit continues after client cancellation. Network errors, timeouts and 5xx responses are retried twice with the same idempotency key, so a call is never billed twice. A commit that still fails rejects the tool call; do not rerun a successful handler to retry accounting.

SDK errors

Tool calls can reject with PortmiiError, exposing code and optional status, reasonCode, correlationId and grant, unless authorize or onUnavailable allows the call. Codes are INVALID_CONFIG, AUTH_REQUIRED, INVALID_TOKEN, ACCESS_DENIED, HTTP_ERROR, INVALID_RESPONSE, NETWORK_ERROR and TIMEOUT. A thrown handler error is preserved even if release fails.

MCP clients receive the error message as an isError result. Denials carry a customer-facing text and a support reference, for example Usage limit reached for this tool. Upgrade your plan or wait for the next period. [ref: <correlationId>].

The same flow in Python.

Read portmii.py

This example brings the TypeScript SDK’s behavior to the official MCP Python SDK 2.x on Python 3.10+. It handles OAuth discovery, token checks, API keys, reservations, commits and releases against the endpoints above. Copy portmii.py into your project. There is no package to install.

01

Add portmii.py

Copy the module below. It depends only on the MCP SDK and PyJWT.

02

Wrap each tool

Put @portmii.tool(name) under @mcp.tool. The function takes ctx: Context.

03

Wrap the HTTP app

portmii.auth(app) serves OAuth discovery and checks every request to your MCP endpoint.

Install the Python dependencies
pip install "mcp>=2,<3" "pyjwt[crypto]>=2.10" uvicorn
server.py
import os

from mcp.server.mcpserver import Context, MCPServer

from portmii import Portmii

# Reads PORTMII_PROVIDER_KEY and optionally PORTMII_BASE_URL from the environment.
portmii = Portmii(
    auth_type="OAUTH_OR_API_KEY",  # or "OAUTH" | "API_KEY"
    server_url=os.environ["MCP_SERVER_URL"],  # public HTTPS URL of this endpoint
    on_unavailable="deny",  # or "allow": run tools while Portmii cannot answer
)
mcp = MCPServer("reports")


@mcp.tool(name="reports.generate")
@portmii.tool("reports.generate")
async def generate_report(report_id: str, ctx: Context) -> str:
    return f"Generated report {report_id}"


# Wrap the whole HTTP app so OAuth discovery is served from the site root.
# host="0.0.0.0" accepts your public Host header; the default allows only localhost.
app = portmii.auth(mcp.streamable_http_app(host="0.0.0.0"))
# Run: uvicorn server:app --port 3333

Match your product configuration.

auth_typerequired

Uses the same values as the SDK: OAUTH, API_KEY or OAUTH_OR_API_KEY (product API_KEY_AND_OAUTH).

server_urlrequired for OAUTH / OAUTH_OR_API_KEY

Your public HTTPS MCP endpoint. It is the OAuth resource and the token audience. Without it, API_KEY mode protects every path.

on_unavailablerequired · no default

"deny" or "allow", like onUnavailable: whether tools run while Portmii cannot answer.

authorize · on_unmeteredoptional

Called as authorize(tool_name=…, reason_code=…, grant=…) for denied calls; return "allow" to run the tool anyway. on_unmetered(tool_name=…, reason=…) runs before an unbilled call. Both may be sync or async.

provider_keydefaults to env

Your pmcp_sk_… key from PORTMII_PROVIDER_KEY. Keep it in server configuration.

base_url · timeoutoptional

PORTMII_BASE_URL or https://api.portmii.com; its origin is the OAuth issuer. timeout is in seconds per Portmii request, 30 by default.

Same guarantees as the SDK.

Without a valid credential, the endpoint returns 401 with a resource_metadata challenge, and clients start Portmii’s Authorization Code + PKCE flow. Tokens are verified against the issuer, the audience, their expiry and the JWKS signature. API-key customers send X-API-Key or Authorization: Bearer pmcp_ck_….

Each call gets a fresh UUID as its idempotency key. A returned result commits. A raised exception releases with tool_error; cancellation releases with canceled. Commit and release finish even if the client disconnects. Network errors, timeouts and 5xx responses are retried twice with the same key. Denials reach the client as an isError result with a support reference, unless authorize or on_unavailable allows the call; such calls run without a reservation and are not billed.

Read portmii.py
portmii.py
"""Portmii for Python MCP servers. Python 3.10+, MCP Python SDK 2.x.

Mirrors @portmii/mcp: `portmii.auth(app)` authenticates requests to your MCP
endpoint and serves OAuth discovery; `portmii.tool(name)` reserves usage before
a tool runs, commits on success and releases on failure. Your server decides
access: `on_unavailable` and the optional `authorize` hook decide whether a tool
runs unmetered when Portmii cannot answer or denies the call.

    pip install "mcp>=2,<3" "pyjwt[crypto]>=2.10"

See https://portmii.com/api#python for setup.
"""
import functools
import inspect
import json
import os
import re
from datetime import datetime, timezone
from urllib.error import HTTPError, URLError
from urllib.parse import quote, urlsplit, urlunsplit
from urllib.request import HTTPRedirectHandler, Request, build_opener
from uuid import uuid4

import anyio
import jwt
from mcp.server.mcpserver import Context
from mcp.server.mcpserver.exceptions import ToolError
from starlette.datastructures import Headers
from starlette.responses import JSONResponse, Response

DEFAULT_BASE_URL = "https://api.portmii.com"
MAX_RESPONSE_BYTES = 1_048_576
# Portmii deduplicates runtime calls by idempotency key, so retries are safe.
RETRY_DELAYS = (0.25, 1.0)
CUSTOMER_API_KEY = re.compile(r"pmcp_ck_[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}")
UUID = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", re.I)
BEARER = re.compile(r"Bearer +([^\s,]+)", re.I)
# Portmii answered, but could not decide: on_unavailable applies, not authorize.
UNAVAILABLE_REASONS = ("feature_disabled", "dependency_unavailable")

# Customer-facing texts. MCP clients receive only the error message.
DENIAL_MESSAGES = {
    "usage_limit_exceeded": "Usage limit reached for this tool. Upgrade your plan or wait for the next period.",
    "grant_missing": "No active subscription for this tool.",
    "grant_inactive": "Your subscription for this tool is inactive.",
    "entitlement_missing": "Your plan does not include this tool.",
    "customer_blocked": "Your account is blocked.",
    "token_expired": "Your session expired. Sign in again.",
    "invalid_customer_credential": "Your credentials are invalid. Sign in again.",
    "tool_unknown": "This tool is currently unavailable.",
    "tool_inactive": "This tool is currently unavailable.",
}


class PortmiiError(ToolError):
    """Returned to the MCP client as an `isError` result with this message."""

    def __init__(self, message, code, *, status=None, reason_code=None, correlation_id=None, grant=None):
        super().__init__(message)
        self.code = code
        self.status = status
        self.reason_code = reason_code
        self.correlation_id = correlation_id
        self.grant = grant


class _NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None  # Never forward credentials to a redirect destination.


_opener = build_opener(_NoRedirect())


class Portmii:
    def __init__(
        self, auth_type, server_url=None, *, on_unavailable=None, authorize=None, on_unmetered=None,
        provider_key=None, base_url=None, timeout=30.0,
    ):
        if auth_type not in ("OAUTH", "API_KEY", "OAUTH_OR_API_KEY"):
            raise PortmiiError("auth_type must be OAUTH, API_KEY or OAUTH_OR_API_KEY", "INVALID_CONFIG")
        # No default: the provider, not Portmii, decides whether tools run while Portmii is unreachable.
        if on_unavailable not in ("deny", "allow"):
            raise PortmiiError("on_unavailable must be 'deny' or 'allow'", "INVALID_CONFIG")
        self.on_unavailable = on_unavailable
        self.authorize = authorize
        self.on_unmetered = on_unmetered
        self.provider_key = provider_key or os.environ.get("PORTMII_PROVIDER_KEY", "")
        if not self.provider_key.strip():
            raise PortmiiError("Portmii provider key is required (provider_key or PORTMII_PROVIDER_KEY)", "INVALID_CONFIG")
        base = _safe_url(base_url or os.environ.get("PORTMII_BASE_URL") or DEFAULT_BASE_URL)
        self.issuer = f"{base.scheme}://{base.netloc}"
        self.auth_type = auth_type
        self.timeout = timeout
        self._jwks = None

        url = _safe_url(server_url) if server_url else None
        if url and url.fragment:
            raise PortmiiError("server_url must not contain a fragment", "INVALID_CONFIG")
        if auth_type != "API_KEY" and not url:
            raise PortmiiError("server_url is required for OAuth", "INVALID_CONFIG")
        self.protected_path = url and (url.path.rstrip("/") or "/")
        self.resource = None
        self.metadata_paths = set()
        if url and auth_type != "API_KEY":
            path = url.path.rstrip("/")
            # A root resource is advertised and expected as audience without the trailing slash.
            self.resource = urlunsplit((url.scheme, url.netloc, path, url.query, ""))
            self.metadata_url = f"{url.scheme}://{url.netloc}/.well-known/oauth-protected-resource{path}"
            self.metadata_paths = {"/.well-known/oauth-protected-resource", urlsplit(self.metadata_url).path}

    def auth(self, app):
        """ASGI middleware: serves OAuth discovery and authenticates requests to the MCP endpoint."""

        async def middleware(scope, receive, send):
            response = await self._authenticate(scope) if scope["type"] == "http" else None
            await (response or app)(scope, receive, send)

        return middleware

    def tool(self, name):
        """Wraps an MCP tool function. The function must accept a `ctx: Context` parameter."""
        if not name.strip():
            raise PortmiiError("Tool name is required", "INVALID_CONFIG")

        def decorator(fn):
            @functools.wraps(fn)
            async def wrapper(*args, **kwargs):
                ctx = next((value for value in (*args, *kwargs.values()) if isinstance(value, Context)), None)
                auth = self._customer_auth(_credential(ctx.headers) if ctx and ctx.headers else None)
                if inspect.iscoroutinefunction(fn):
                    execute = functools.partial(fn, *args, **kwargs)
                else:
                    execute = functools.partial(anyio.to_thread.run_sync, functools.partial(fn, *args, **kwargs))
                return await self._run(name, auth, execute)

            return wrapper

        return decorator

    async def _authenticate(self, scope):
        """Returns a response to send instead of the MCP app, or None to continue."""
        path, method = scope["path"], scope["method"]
        if path in self.metadata_paths and method in ("GET", "OPTIONS"):
            # Public metadata is fetched cross-origin by browser-based MCP clients.
            cors = {"access-control-allow-origin": "*"}
            if method == "OPTIONS":
                return Response(status_code=204, headers={**cors, "access-control-allow-methods": "GET", "access-control-allow-headers": "*"})
            return JSONResponse({"resource": self.resource, "authorization_servers": [self.issuer]}, headers=cors)
        if method == "OPTIONS" or (self.protected_path and (path.rstrip("/") or "/") != self.protected_path):
            return None

        headers = Headers(scope=scope)
        if "authorization" not in headers and "x-api-key" not in headers:
            return self._unauthorized("Authentication required")
        token = _credential(headers)
        if token is None:
            return self._unauthorized("Malformed or ambiguous credentials", True)
        if token.startswith("pmcp_ck_"):
            if self.auth_type == "OAUTH" or not CUSTOMER_API_KEY.fullmatch(token):
                return self._unauthorized("API key is invalid or not enabled", True)
            return None
        if not self.resource:
            return self._unauthorized("OAuth is not enabled", True)
        try:
            await self._verify_access_token(token)
        except PortmiiError as error:
            if error.code != "INVALID_TOKEN":
                raise
            return self._unauthorized("Access token is invalid or expired", True)
        return None

    def _unauthorized(self, description, invalid_token=False):
        params = (['error="invalid_token"'] if invalid_token else []) + (
            [f'resource_metadata="{self.metadata_url}"'] if self.resource else []
        )
        return JSONResponse(
            {"error": "invalid_token" if invalid_token else "unauthorized", "error_description": description},
            status_code=401,
            headers={"www-authenticate": " ".join(["Bearer", ", ".join(params)]).strip(), "cache-control": "no-store"},
        )

    async def _verify_access_token(self, token):
        if len(token) > 8192:
            raise PortmiiError("OAuth access token is malformed", "INVALID_TOKEN")
        if self._jwks is None:
            self._jwks = jwt.PyJWKClient(await self._discover_jwks_uri(), timeout=self.timeout)
        try:
            key = await anyio.to_thread.run_sync(self._jwks.get_signing_key_from_jwt, token)
            claims = jwt.decode(
                token, key, algorithms=[key.algorithm_name], audience=self.resource, issuer=self.issuer,
                options={"require": ["exp", "client_id"]},
            )
            if not isinstance(claims["client_id"], str):
                raise jwt.InvalidTokenError("client_id must be a string")
        except jwt.PyJWTError as error:
            raise PortmiiError("OAuth access token is invalid", "INVALID_TOKEN") from error
        return claims

    async def _discover_jwks_uri(self):
        url = self.issuer + "/.well-known/oauth-authorization-server"
        status, metadata = await anyio.to_thread.run_sync(self._request, "GET", url, None, {"accept": "application/json"})
        if not 200 <= status < 300:
            raise PortmiiError("Portmii OAuth discovery failed", "HTTP_ERROR", status=status)
        if not isinstance(metadata, dict) or metadata.get("issuer") != self.issuer or not isinstance(metadata.get("jwks_uri"), str):
            raise _invalid_response()
        _safe_url(metadata["jwks_uri"], "INVALID_RESPONSE")
        return metadata["jwks_uri"]

    def _customer_auth(self, token):
        if token is None:
            raise PortmiiError("Customer authentication is required. Wrap the MCP app with portmii.auth.", "AUTH_REQUIRED")
        if not token.strip() or len(token) > 8192:
            raise PortmiiError("Customer credential is malformed", "INVALID_TOKEN")
        if not token.startswith("pmcp_ck_"):
            if self.auth_type == "API_KEY":
                raise PortmiiError("Customer authentication method is not enabled", "ACCESS_DENIED")
            return {"accessToken": token}
        if not CUSTOMER_API_KEY.fullmatch(token):
            raise PortmiiError("Customer API key is malformed", "INVALID_TOKEN")
        if self.auth_type == "OAUTH":
            raise PortmiiError("Customer authentication method is not enabled", "ACCESS_DENIED")
        return {"customerCredential": token}

    async def _run(self, tool, auth, execute):
        # MCP request IDs are client-controlled and may repeat across customers and sessions.
        request_id = str(uuid4())
        try:
            reservation = await self._post("/v1/mcp/runtime/usage/reservations", {**auth, "tool": tool}, request_id)
        except PortmiiError as error:
            # Portmii's answer is only input; the provider decides whether the tool runs unmetered.
            unavailable = _is_unavailable(error)
            access = None
            if unavailable:
                access = self.on_unavailable
            elif self.authorize and error.reason_code and 400 <= (error.status or 0) < 500:
                access = await _call(self.authorize, tool_name=tool, reason_code=error.reason_code, grant=error.grant)
            if access != "allow":
                raise
            if self.on_unmetered:
                await _call(self.on_unmetered, tool_name=tool, reason="unavailable" if unavailable else "authorized")
            return await execute()
        reservation_id = reservation.get("reservationId") if isinstance(reservation, dict) else None
        if not (
            isinstance(reservation_id, str)
            and UUID.fullmatch(reservation_id)
            and reservation.get("status") == "RESERVED"
            and _is_future(reservation.get("expiresAt"))
        ):
            raise _invalid_response()
        path = "/v1/mcp/runtime/usage/reservations/" + quote(reservation_id, safe="")

        try:
            result = await execute()
        except BaseException as error:
            outcome = "canceled" if isinstance(error, anyio.get_cancelled_exc_class()) else "tool_error"
            with anyio.CancelScope(shield=True):
                try:
                    await self._post(path + "/release", {"outcome": outcome}, request_id)
                except Exception:
                    pass  # Best effort: preserve the handler's error; expiry recovers the hold.
            raise

        # Completed work is committed even when the client has disconnected.
        with anyio.CancelScope(shield=True):
            committed = await self._post(path + "/commit", {}, request_id)
        if not isinstance(committed, dict) or committed.get("status") != "COMMITTED" or committed.get("reservationId") != reservation_id:
            raise _invalid_response()
        return result

    async def _post(self, path, body, request_id):
        """Retries network errors, timeouts and 5xx responses with the same idempotency key."""
        for delay in (*RETRY_DELAYS, None):
            try:
                status, payload = await anyio.to_thread.run_sync(self._request, "POST", self.issuer + path, body, {
                    "authorization": "Bearer " + self.provider_key,
                    "content-type": "application/json",
                    "idempotency-key": request_id,
                })
                if not 200 <= status < 300:
                    raise _response_error(status, payload, path.endswith("/commit"))
                return payload
            except PortmiiError as error:
                if delay is None or not _is_retryable(error):
                    raise
                await anyio.sleep(delay)

    def _request(self, method, url, body, headers):
        data = json.dumps(body).encode() if body is not None else None
        try:
            try:
                with _opener.open(Request(url, data, headers, method=method), timeout=self.timeout) as response:
                    status, raw = response.status, response.read(MAX_RESPONSE_BYTES + 1)
            except HTTPError as error:
                with error:
                    status, raw = error.code, error.read(MAX_RESPONSE_BYTES + 1)
        except TimeoutError as error:
            raise PortmiiError("Portmii request timed out", "TIMEOUT") from error
        except (URLError, OSError) as error:
            if isinstance(getattr(error, "reason", None), TimeoutError):
                raise PortmiiError("Portmii request timed out", "TIMEOUT") from error
            raise PortmiiError("Portmii request failed", "NETWORK_ERROR") from error
        try:
            if len(raw) > MAX_RESPONSE_BYTES:
                raise ValueError("response too large")
            return status, json.loads(raw) if raw else {}
        except ValueError as error:
            raise _invalid_response() from error


def _credential(headers):
    """The customer's token from `Authorization: Bearer` or `X-API-Key`, or None if malformed or ambiguous."""
    authorization, api_key = headers.get("authorization"), headers.get("x-api-key")
    if authorization is not None and api_key is not None:
        return None
    if authorization is not None:
        match = BEARER.fullmatch(authorization)
        return match and match[1]
    return api_key if api_key and api_key.startswith("pmcp_ck_") else None


def _is_retryable(error):
    return error.code in ("NETWORK_ERROR", "TIMEOUT") or (error.status or 0) >= 500


def _is_unavailable(error):
    """Portmii could not decide: network error, timeout, 5xx or a disabled runtime dependency."""
    return _is_retryable(error) or error.reason_code in UNAVAILABLE_REASONS


async def _call(hook, **kwargs):
    """Calls a sync or async provider hook."""
    result = hook(**kwargs)
    return await result if inspect.isawaitable(result) else result


def _response_error(status, payload, commit):
    details = payload if isinstance(payload, dict) else {}
    reason = details.get("reasonCode") if isinstance(details.get("reasonCode"), str) else None
    correlation = details.get("correlationId") if isinstance(details.get("correlationId"), str) else None
    if commit:
        message = "Portmii usage commit failed"
    else:
        message = DENIAL_MESSAGES.get(reason) or "Portmii denied tool execution" + (f" ({reason})" if reason else "")
    return PortmiiError(
        message + (f" [ref: {correlation}]" if correlation else ""),
        "ACCESS_DENIED" if status in (401, 403, 404, 409, 429) else "HTTP_ERROR",
        status=status, reason_code=reason, correlation_id=correlation,
        grant=details.get("grant") if isinstance(details.get("grant"), dict) else None,
    )


def _safe_url(value, code="INVALID_CONFIG"):
    """HTTPS only; plain HTTP is accepted for loopback hosts during local development."""
    url = urlsplit(value)
    loopback = url.hostname in ("localhost", "127.0.0.1", "::1")
    if not url.hostname or (url.scheme != "https" and not (loopback and url.scheme == "http")):
        raise PortmiiError("Portmii URL must use HTTPS", code)
    if url.username or url.password:
        raise PortmiiError("Portmii URL must not contain credentials", code)
    return url


def _is_future(value):
    try:
        return datetime.fromisoformat(value.replace("Z", "+00:00")) > datetime.now(timezone.utc)
    except (AttributeError, ValueError, TypeError):
        return False


def _invalid_response():
    return PortmiiError("Portmii returned an invalid response", "INVALID_RESPONSE")

server.py passes host="0.0.0.0" to streamable_http_app so your public domain is accepted. The default host enables DNS-rebinding protection that accepts only localhost Host headers. Errors are PortmiiError, with code, status, reason_code and correlation_id.

Your stack. Your MCP server.

Use the HTTP API directly, or let the TypeScript SDK or the Python example handle the runtime flow.

Explore the SDK