[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6GCTZKT0YCFYJF4XCZSB3QH":3,"skill-same:01M6GCTZKT0YCFYJF4XCZSB3QH":74},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":37,"linkOnly":38,"markdownContent":39,"markdownBody":40,"frontMatter":41,"refName":52,"commitSha":53,"skillDirectory":54,"forksCount":55,"repositoryHtmlUrl":56,"repositoryHomepageUrl":6,"ownerHtmlUrl":57,"ownerBlogUrl":6,"ownerDescription":58,"updatedAt":59,"install":60,"resources":73},"01M6GCTZKT0YCFYJF4XCZSB3QH","mcp-oauth-remote-gateway",null,"Manual OAuth for remote MCP servers on headless gateways.","zapabob\u002FSkills","zapabob","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F130830376?v=4","01M6DBMYZAGRTFQDSQYW3W764P","峯岸 亮","01M6DBMZ3GKDSJ01NZ9XTZD7JD",2,"MIT","https:\u002F\u002Fgithub.com\u002Fzapabob\u002FSkills\u002Fblob\u002Fmain\u002Farchive\u002Fskill-md-reviewed\u002Fsha256\u002Faf\u002Faff327983c8e5798762c0281c1de146d97e15d12129878435540bf539346c506\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36],"OAuth","mcp oauth remote gateway","remote","MCP","gateway","fastmcp","mcp servers","deployment","gateways","linux","pkce","hermes","hermes agent","native","mcporter","manual","headless","macos","2026-11-10 10:12:30",false,"---\r\nname: mcp-oauth-remote-gateway\r\ndescription: Manual OAuth for remote MCP servers on headless gateways.\r\nversion: 1.0.0\r\nauthor: Ben Barclay (benbarclay), Hermes Agent\r\nlicense: MIT\r\nplatforms: [linux, macos]\r\nmetadata:\r\n  hermes:\r\n    tags: [MCP, OAuth, PKCE, Remote-Deployment]\r\n    related_skills: [native-mcp, mcporter, fastmcp]\r\n---\r\n\r\n# MCP OAuth on a Remote Hermes Gateway\r\n\r\n## Overview\r\n\r\nHermes' built-in MCP OAuth client runs a one-shot HTTP listener on `127.0.0.1:\u003Cport>`\r\ninside the Hermes process and registers that loopback address as the OAuth\r\n`redirect_uri`. That works perfectly for a local CLI on the user's own machine.\r\nIt breaks completely when Hermes runs as a remote gateway (container, VPS,\r\nmessaging bot), because the user's browser resolves `127.0.0.1` to the user's own\r\nlaptop, not the remote container — so the authorization code never reaches Hermes.\r\n\r\nThis skill does the OAuth dance by hand and writes the resulting tokens into the\r\nexact files Hermes' token storage expects, so a subsequent `\u002Freload-mcp` finds\r\ncached tokens and skips the browser flow entirely.\r\n\r\n## When to Use\r\n\r\nUse this skill when **all** of the following are true:\r\n\r\n1. The user wants to add a remote HTTP MCP server that requires OAuth (not a static Bearer token).\r\n2. Hermes is running as a **remote gateway** (container, VPS, Docker, managed service) — NOT a local CLI on the user's laptop.\r\n3. The server supports OAuth 2.1 with PKCE and RFC 7591 Dynamic Client Registration (most modern MCP servers do — Better Stack, Linear, Cloudflare, Datadog, etc.). If it doesn't support DCR (GitHub is the notable exception), this skill does not apply — use a pre-registered OAuth App or a Personal Access Token instead.\r\n\r\nDo NOT use this for:\r\n- **Local CLI Hermes** — just set `auth: oauth` in `mcp_servers.\u003Cname>` and `\u002Freload-mcp`. The built-in flow opens a browser and captures the callback on localhost. Works perfectly.\r\n- **Servers that accept a static Bearer token (API key)** — always prefer `headers.Authorization: \"Bearer \u003Ctoken>\"` when the user is willing. Simpler, no refresh dance.\r\n- **GitHub Copilot MCP** (`api.githubcopilot.com\u002Fmcp\u002F`) — GitHub does not expose DCR. Use a PAT or a pre-registered OAuth App (see pitfall 12).\r\n\r\n## Why the Built-in OAuth Flow Fails on a Remote Gateway\r\n\r\nHermes' native MCP OAuth client (`tools\u002Fmcp_oauth.py`):\r\n\r\n1. Picks a free local port `P`.\r\n2. Registers a dynamic OAuth client with the AS, sending `redirect_uri = http:\u002F\u002F127.0.0.1:P\u002Fcallback`.\r\n3. Starts an HTTP server on `127.0.0.1:P` **inside the Hermes process**.\r\n4. Prints the authorize URL and waits for the code at its local endpoint.\r\n\r\nWhen Hermes runs remotely, the `127.0.0.1` in the `redirect_uri` is the remote\r\ncontainer's loopback, not the user's. After authorizing, the user's browser 302s\r\nto `http:\u002F\u002F127.0.0.1:P\u002Fcallback?code=...`, which resolves to the user's own\r\nlaptop and fails to connect. The callback never reaches the Hermes process, the\r\nflow times out, and `\u002Freload-mcp` returns \"No MCP tools available\" with no detail.\r\n\r\nSymptoms to recognize: `[xdg-open] \u003Cdefunct>` processes under the hermes user, an\r\nempty or missing tokens directory (`$HERMES_HOME\u002Fmcp-tokens\u002F`), and a reload that\r\nresponds without any \"Added\u002FReconnected: X\" line in `change_detail`.\r\n\r\n## Cheap First Fallbacks: the Built-in Flow's Own Escape Hatches\r\n\r\nBefore any manual token surgery, check whether the built-in flow's fallbacks\r\nalready cover the deployment. When Hermes detects a remote session it prints two\r\noptions alongside the authorize URL (`tools\u002Fmcp_oauth.py`):\r\n\r\n1. **Paste-back** — on an interactive TTY, a stdin reader races the HTTP\r\n   listener. The user authorizes, the browser fails to connect to\r\n   `127.0.0.1:\u003Cport>`, and they paste the full address-bar URL\r\n   (`?code=...&state=...`) back at the prompt. Works for SSH'd-in CLI sessions.\r\n2. **SSH port-forward** — `ssh -N -L \u003Cport>:127.0.0.1:\u003Cport> \u003Cuser>@\u003Chost>`\r\n   makes the redirect reach the remote listener normally.\r\n\r\nBoth require an interactive terminal to the Hermes host. The rest of this skill\r\nis for when there is NO interactive TTY — Hermes running purely as a messaging\r\ngateway\u002Fbot where `\u002Freload-mcp` triggers the flow with nobody at a prompt.\r\n\r\n## Preferred Front Door: the Hermes Dashboard (try this BEFORE manual token surgery)\r\n\r\nA remote Hermes gateway often also runs the **dashboard** web UI as a SEPARATE\r\nprocess (e.g. `hermes dashboard --host 0.0.0.0 --port \u003Cport>`; check with\r\n`ps aux | grep 'hermes dashboard'`). It exposes a connector\u002FMCP console —\r\nendpoints like `\u002Fapi\u002Fmcp\u002Fservers`, `\u002Fapi\u002Fmcp\u002Fstatus`, and `\u002Fconnectors` (all\r\nlogin-gated; a cookieless curl returning 401\u002F302 confirms they exist).\r\n\r\n**Why the dashboard solves the core problem:** when the user drives OAuth from\r\nthe dashboard *in their own browser*, the redirect lands in a context the\r\ndashboard can capture — sidestepping the `127.0.0.1`-callback failure that breaks\r\nthe CLI\u002Fmanual flow. So the correct escalation order for \"add or re-auth an OAuth\r\nMCP server on a remote gateway\" is:\r\n\r\n1. **Dashboard, in the user's browser** — the intended front door. Add servers, run OAuth, reload, all authenticated as the user. No copy-paste-callback dance, no hand-writing token files.\r\n2. **Manual token surgery (the rest of this skill)** — the FALLBACK for when there's no browser session to the dashboard (pure-chat\u002Fheadless context).\r\n\r\n**Finding the dashboard's PUBLIC URL.** The dashboard binds internally to\r\n`0.0.0.0:\u003Cport>`, but the user needs the externally-reachable URL. Most deploy\r\nplatforms inject it into the environment — grep for it rather than making the\r\nuser hunt:\r\n\r\n```bash\r\nenv | grep -iE \"HERMES_DASHBOARD_PUBLIC_URL|RAILWAY_PUBLIC_DOMAIN|RAILWAY_STATIC_URL|RAILWAY_SERVICE_.*_URL|PUBLIC_URL|BASE_URL|DOMAIN\" \\\r\n  | sed -E 's\u002F(TOKEN|SECRET|KEY|PASSWORD)=.*\u002F\\1=***REDACTED***\u002FI'\r\n```\r\n\r\n`HERMES_DASHBOARD_PUBLIC_URL` is authoritative when present. On Railway also check\r\n`RAILWAY_PUBLIC_DOMAIN` \u002F `RAILWAY_STATIC_URL` (the `*.up.railway.app` host) and\r\n`RAILWAY_SERVICE_*_URL` vars, which sometimes carry a friendlier custom domain.\r\nHand the user the full `https:\u002F\u002F` URL and point them at the Connectors\u002FMCP\r\nsection. ALWAYS pipe through the `sed` redaction above — these env greps sit next\r\nto `*_TOKEN`\u002F`*_SECRET` vars.\r\n\r\n**What the dashboard does NOT fix (still host-side \u002F shell):** stdio servers that\r\nneed shell auth state (a CLI `login` command whose credentials may not persist\r\nacross restarts) and anything reading credentials from `$HERMES_HOME\u002F.env`. Those\r\nare out of the dashboard's scope regardless.\r\n\r\n## The Workaround\r\n\r\nDo the OAuth dance manually, then write the resulting tokens into the exact files\r\nHermes' `HermesTokenStorage` would have written, so on `\u002Freload-mcp` Hermes finds\r\ncached tokens and skips the browser flow entirely.\r\n\r\nRun the shell commands below through the `terminal` tool on the gateway host and\r\ndo the Python steps (PKCE generation, token exchange, file writes) via\r\n`execute_code` or a `terminal` python3 invocation — file writes must happen in\r\nthe SAME code block as the token exchange (see pitfall 16).\r\n\r\n### 1. Confirm it's a remote gateway\r\n\r\n```bash\r\nenv | grep -iE \"HERMES|RAILWAY|CONTAINER\"\r\necho \"$DISPLAY $WAYLAND_DISPLAY $SSH_CLIENT\"\r\n```\r\n\r\nNo display + a remote indicator = remote gateway. `tools\u002Fmcp_oauth.py::_can_open_browser()`\r\nuses these same env vars, so if Hermes' own auto-detect says \"headless\", the\r\nbuilt-in flow won't work.\r\n\r\n### 2. Find HERMES_HOME and the config path\r\n\r\n```bash\r\nHERMES_HOME=$(python3 -c 'from hermes_constants import get_hermes_home; print(get_hermes_home())')\r\necho \"config: $HERMES_HOME\u002Fconfig.yaml\"\r\necho \"tokens: $HERMES_HOME\u002Fmcp-tokens\u002F\"\r\n```\r\n\r\n### 3. Discover OAuth metadata from the MCP server\r\n\r\nMCP servers advertise their OAuth setup via RFC 9728 (OAuth 2.0 Protected\r\nResource Metadata). The `WWW-Authenticate` header on a 401 tells you where to look:\r\n\r\n```bash\r\ncurl -sI https:\u002F\u002Fmcp.example.com | grep -i www-authenticate\r\n# → Bearer realm=\"mcp\", resource_metadata=\"https:\u002F\u002Fmcp.example.com\u002F.well-known\u002Foauth-protected-resource\"\r\n```\r\n\r\n**Not every server returns `WWW-Authenticate`.** Some return a bare\r\n`{\"errors\":[\"Unauthorized\"]}` 401 with no auth-discovery hint. When that happens,\r\nprobe well-known paths directly:\r\n\r\n```bash\r\nfor p in \\\r\n  \u002F.well-known\u002Foauth-protected-resource \\\r\n  \u002F.well-known\u002Foauth-authorization-server \\\r\n  \u002F.well-known\u002Fopenid-configuration ; do\r\n  echo \"=== $p ===\"\r\n  curl -s -A \"python-httpx\u002F0.27\" \"https:\u002F\u002Fmcp.example.com$p\" | head -c 400; echo\r\ndone\r\n```\r\n\r\nFetch the resource metadata to get `authorization_servers`, then fetch the AS's\r\n`\u002F.well-known\u002Foauth-authorization-server` to get `authorization_endpoint`,\r\n`token_endpoint`, and `registration_endpoint`.\r\n\r\nPitfall: many servers sit behind Cloudflare and 403 bare `urllib` user agents.\r\nAlways set `User-Agent: python-httpx\u002F0.27` (or similar) on requests in this flow.\r\n\r\n### 4. Dynamic Client Registration (RFC 7591)\r\n\r\nPOST to the `registration_endpoint` with:\r\n\r\n```json\r\n{\r\n  \"client_name\": \"Hermes Agent (manual OAuth)\",\r\n  \"redirect_uris\": [\"http:\u002F\u002F127.0.0.1:8765\u002Fcallback\"],\r\n  \"grant_types\": [\"authorization_code\", \"refresh_token\"],\r\n  \"response_types\": [\"code\"],\r\n  \"token_endpoint_auth_method\": \"none\",\r\n  \"scope\": \"\u003Cscopes_from_resource_metadata>\"\r\n}\r\n```\r\n\r\nOmit `scope` entirely if the AS's `scopes_supported` is empty — see step 5\r\npitfall. Use port `8765` (or any port — nothing will listen).\r\n`token_endpoint_auth_method: none` marks this as a public PKCE client. Save the\r\nreturned `client_id`.\r\n\r\n### 5. Build the authorize URL with PKCE\r\n\r\nGenerate:\r\n- `code_verifier`: `secrets.token_urlsafe(64)[:128]`\r\n- `code_challenge`: `base64url(sha256(code_verifier))` (no padding)\r\n- `state`: `secrets.token_urlsafe(24)`\r\n\r\nQuery params: `response_type=code`, `client_id`, `redirect_uri`, `code_challenge`,\r\n`code_challenge_method=S256`, `state`, plus `resource=\u003Cmcp_server_url>` (RFC 8707 —\r\nmany servers require this to bind the token to the specific MCP resource). Include\r\n`scope=\u003Cspace-separated>` ONLY if the AS metadata's `scopes_supported` is a\r\nnon-empty array AND\u002FOR the resource metadata declares specific scopes. If\r\n`scopes_supported: []`, omit the `scope` parameter — the server grants its full\r\ndefault set on its own. Fabricating scope strings against an empty\r\n`scopes_supported` can cause `invalid_scope` errors on some ASes.\r\n\r\n**Stash `code_verifier` and `state` to disk** (e.g. `\u002Ftmp\u002F.mcp-oauth-work\u002F\u003Cserver>.json`,\r\n0600 perms). You need them for step 7, possibly across multiple chat turns.\r\n\r\n### 6. Give the user the authorize URL\r\n\r\n```\r\nOpen this URL in your browser:\r\n\u003Cauthorize_url>\r\n\r\nAfter approving, your browser will try to load http:\u002F\u002F127.0.0.1:8765\u002Fcallback\r\nand fail to connect — THAT'S EXPECTED. Just copy the entire URL from the\r\naddress bar (it will contain ?code=...&state=...) and paste it back here.\r\n```\r\n\r\n### 7. Exchange the code for tokens\r\n\r\nWhen the user pastes the callback URL:\r\n\r\n1. Parse `code` and `state` from the query string.\r\n2. **Verify `state` matches the stashed value** (CSRF check — do not skip).\r\n3. POST `application\u002Fx-www-form-urlencoded` to the `token_endpoint`:\r\n   - `grant_type=authorization_code`\r\n   - `code=\u003Cfrom callback>`\r\n   - `redirect_uri=\u003Csame as step 4>`\r\n   - `client_id=\u003Cfrom step 4>`\r\n   - `code_verifier=\u003Cstashed>`\r\n   - `resource=\u003Cmcp_server_url>` (if the AS required it in step 5, include here too)\r\n4. Response contains `access_token`, `refresh_token`, `token_type`, `expires_in`, `scope`.\r\n\r\n### 8. Write tokens in Hermes' exact schema\r\n\r\n`tools\u002Fmcp_oauth.py::HermesTokenStorage` expects two files under\r\n`$HERMES_HOME\u002Fmcp-tokens\u002F` (create dir with `0o700`, files with `0o600`):\r\n\r\n**`\u003Cserver_name>.json`** — the `OAuthToken` pydantic model:\r\n```json\r\n{\r\n  \"access_token\": \"...\",\r\n  \"token_type\": \"Bearer\",\r\n  \"expires_in\": 7200,\r\n  \"refresh_token\": \"...\",\r\n  \"scope\": \"read write\"\r\n}\r\n```\r\n\r\n**`\u003Cserver_name>.client.json`** — the `OAuthClientInformationFull` model:\r\n```json\r\n{\r\n  \"client_id\": \"...\",\r\n  \"redirect_uris\": [\"http:\u002F\u002F127.0.0.1:8765\u002Fcallback\"],\r\n  \"grant_types\": [\"authorization_code\", \"refresh_token\"],\r\n  \"response_types\": [\"code\"],\r\n  \"token_endpoint_auth_method\": \"none\",\r\n  \"scope\": \"read write\",\r\n  \"client_name\": \"...\"\r\n}\r\n```\r\n\r\nWrite each file via `json.dumps(..., indent=2)`. Sanitize the filename with\r\n`re.sub(r'[^\\w\\-]', '_', server_name)[:128]` — this matches `_safe_filename()` in\r\nHermes' token storage.\r\n\r\n### 9. Add the server to config.yaml\r\n\r\n```yaml\r\nmcp_servers:\r\n  \u003Cname>:\r\n    url: \"https:\u002F\u002Fmcp.example.com\"\r\n    auth: oauth\r\n    timeout: 180\r\n    connect_timeout: 60\r\n```\r\n\r\n### 10. Smoke-test the token BEFORE asking the user to reload\r\n\r\nManually POST an MCP `initialize` request to confirm the token works end-to-end —\r\nthis catches scope misconfigurations, wrong `resource` values, and CF blocks\r\nbefore the user is confused by another \"No MCP tools available\" reload:\r\n\r\n```python\r\nbody = json.dumps({\r\n    \"jsonrpc\": \"2.0\", \"id\": 1, \"method\": \"initialize\",\r\n    \"params\": {\r\n        \"protocolVersion\": \"2025-06-18\",\r\n        \"capabilities\": {},\r\n        \"clientInfo\": {\"name\": \"hermes-debug\", \"version\": \"1.0\"},\r\n    },\r\n}).encode()\r\n# POST to the MCP URL with:\r\n#   Authorization: Bearer \u003Caccess_token>\r\n#   Accept: application\u002Fjson, text\u002Fevent-stream\r\n#   Content-Type: application\u002Fjson\r\n#   MCP-Protocol-Version: 2025-06-18\r\n#   User-Agent: python-httpx\u002F0.27\r\n```\r\n\r\nExpect HTTP 200 with `Content-Type: text\u002Fevent-stream` and a JSON-RPC result\r\ncontaining `serverInfo` and `capabilities`. **Do not use `urllib` with its default\r\nUA** — Cloudflare will 403 you even though Hermes (which uses httpx) will succeed.\r\n`scripts\u002Fdiagnose-oauth-mcp.py` automates this smoke test.\r\n\r\n### 11. Tell the user to run `\u002Freload-mcp`\r\n\r\nOn reload, Hermes sees `auth: oauth`, calls `HermesTokenStorage.get_tokens()`,\r\nfinds your cached tokens, skips the browser flow, and registers `mcp_\u003Cname>_*`\r\ntools. Refresh happens automatically before `expires_in` elapses.\r\n\r\n## Pitfalls & Lessons Learned\r\n\r\n1. **Do not assume \"headless\" means \"OAuth impossible.\"** The built-in flow works fine for local CLI; the issue is strictly remote deployments where the user's browser and the Hermes process are on different machines. Check the execution environment before claiming OAuth isn't an option.\r\n\r\n2. **Read the source, not just the skill docs.** `tools\u002Fmcp_oauth.py` and the MCP config reference in `website\u002Fdocs\u002F` are the authoritative references. Grep the tree before telling the user a feature \"doesn't exist.\"\r\n\r\n3. **Cloudflare UA filter.** Many MCP\u002FOAuth providers front their infra with Cloudflare, which 403s `python-urllib\u002F*` user agents on metadata endpoints even though those endpoints are public. Set `User-Agent: python-httpx\u002F0.27` (or any browser-like string) on every request in this flow. Hermes itself uses httpx, so this is never a problem in the real connection path.\r\n\r\n4. **Include `resource` in both authorize and token requests.** RFC 8707 resource indicators are not optional for most modern MCP servers — they bind the issued token to the specific MCP resource URL. Leaving it out sometimes still works but may yield a token that later fails at the MCP server with a scope\u002Faudience error.\r\n\r\n5. **Trailing slash matters.** Some servers advertise the resource as `https:\u002F\u002Fmcp.example.com\u002F` with a trailing slash and reject tokens issued against the no-slash variant. Copy the `resource` value verbatim from the `.well-known\u002Foauth-protected-resource` response.\r\n\r\n6. **`\u002Freload-mcp` is silent on failure.** If the reload shows \"No MCP tools available\" with no `change_detail` line, a server is in config but failed to connect and no error bubbled up. Tail the error log, smoke-test the token directly with a manual `initialize` POST, and — if everything looks good — ask for a full process restart.\r\n\r\n7. **Circuit breaker can survive `\u002Freload-mcp`.** `tools\u002Fmcp_tool.py` keeps a module-level error-count dict with a small threshold. Once tripped (e.g. after token expiry produces several consecutive failures), the tool handler can short-circuit before calling the server, so no successful call resets the counter. Symptom: reload says \"Reconnected: X\" but subsequent calls still fail with \"server unreachable\" in the same conversation. Recovery order: try `\u002Freload-mcp` FIRST (cheap, no chat-process blip) — on current builds it can clear the counter; only escalate to a full gateway process restart if a live call STILL short-circuits after reload. Do not lead with \"you must restart.\"\r\n\r\n8. **Refresh on an expired access_token + a tripped breaker is a deadlock.** The auto-refresh logic runs inside the MCP call path, which the breaker short-circuits once tripped. Manually refreshing the token on disk does not help by itself — pair a manual token refresh with a full restart, not a `\u002Freload-mcp`.\r\n\r\n9. **`invalid_grant` on a manual refresh means the refresh token is DEAD — re-auth is the only fix, do not loop.** When the access_token has been expired long enough, the refresh_token can also be revoked\u002Fexpired server-side. A `grant_type=refresh_token` POST then returns HTTP 400 `{\"error\":\"invalid_grant\",...}` (wording varies: \"Grant not found\", \"Token expired\", \"refresh token is invalid\"). There is NO recovery from the gateway side. Hand back to the user with two options: (a) re-run the full manual OAuth dance (steps 3–10), or (b) if the provider offers a static personal API key, switch to that — no refresh\u002Fexpiry cycle, more durable for an unattended remote gateway. Detect early: before any create\u002Fupdate operation against an OAuth MCP, check `expires_at` vs `time.time()`; if already expired, attempt the refresh first and surface `invalid_grant` immediately rather than failing mid-task.\r\n\r\n10. **A successful refresh that STILL yields a rejected token = server-side SESSION revocation; only a fresh authorization_code flow fixes it.** Distinct from pitfall 9. The stored token file can look healthy (`expires_at` well out, refresh_token present), yet a live `initialize` POST returns `401 invalid_token` with a JSON-RPC body like `{\"error\":{\"code\":-32002,\"message\":\"Session expired. Please re-authenticate.\"}}`. The `grant_type=refresh_token` POST may **succeed** (HTTP 200, new access_token) — yet the brand-new token gets the SAME `-32002`. The provider revoked the underlying MCP *session* server-side; the OAuth refresh chain re-mints credentials but cannot re-establish a revoked session. Decision rule when an OAuth MCP reports \"not connected\": (1) smoke-test the stored access_token with a manual `initialize` POST; (2) if `401 invalid_token`, attempt a refresh and smoke-test the NEW token; (3a) new token works → write it + restart to clear the breaker; (3b) new token STILL gets `-32002`\u002F\"Session expired\" → stop, this is session revocation, hand the user the authorize URL for a full re-auth. `scripts\u002Fdiagnose-oauth-mcp.py` automates steps 1–2 and prints which branch you're in. For an unattended gateway whose session keeps getting revoked, prefer a static Personal API key. See `references\u002Fstripe-mcp-oauth-revocation.md` for a worked example of a provider that revokes weekly.\r\n\r\n11. **Client info file is NOT optional.** Hermes needs `\u003Cserver>.client.json` to know the `client_id` for refresh grants. Skipping it means the first refresh fails and the user has to re-auth — writing both files is the whole point of this skill.\r\n\r\n12. **Never hand-type the redirect URL for the user to open.** Generate the authorize URL programmatically with `urllib.parse.urlencode()`. Spaces in scopes and special chars in `state` break string-concatenated URLs.\r\n\r\n13. **Security: the stash file contains the `code_verifier`.** Delete `\u002Ftmp\u002F.mcp-oauth-work\u002F\u003Cserver>.json` immediately after successful token exchange. There's no reason to keep a proof-of-identity secret around once it's consumed.\r\n\r\n14. **Write what the token endpoint actually returned.** The AS may grant a narrower (or wider) scope than requested. Write the `scope` from the token-exchange response to `\u003Cserver>.json`, not what you asked for in step 5. When `scopes_supported: []`, the explicit scope list you send IS authoritative both ways: some servers grant exactly what you list (pass narrow scopes for least-privilege, or enumerate the full set if the user needs everything), and some won't echo the granted scope back at registration time — only the token-exchange response is authoritative.\r\n\r\n15. **OAuth tokens often double as Bearer tokens against the provider's public REST API.** The access_token in `\u003Cserver>.json` is frequently not \"MCP-only\" — `Authorization: Bearer \u003Ctoken>` against the provider's documented REST API succeeds whenever the corresponding resource scope was granted. This is the OAuth 2.0 spec, not a provider quirk. When the MCP server is read-only but you need a write operation, check whether the OAuth token can hit the provider's REST API directly before suggesting a separate API key.\r\n\r\n16. **Secret redaction can mask tokens in tool output.** If secret redaction is enabled, tokens and long opaque strings render as `***` in tool-result output, so you cannot `print(response)` to keep the access_token visible across turns. Combined with single-use `code` values from authorization_code grants: if you print the token-exchange response, you may lose the token AND consume the code, forcing a restart with a fresh authorize URL. **Always write the access_token directly to its final destination file in the SAME code block that performs the token exchange.** If you must print for debugging, print only `len(access_token)`, `token_type`, `scope`, `expires_in` — never the secret.\r\n\r\n17. **GitHub MCP (`api.githubcopilot.com\u002Fmcp\u002F`) uses a pre-registered confidential OAuth App, not DCR + PKCE-public.** Its client info ships with a real `client_secret` and `token_endpoint_auth_method: client_secret_post`. The token-exchange POST to `https:\u002F\u002Fgithub.com\u002Flogin\u002Foauth\u002Faccess_token` must include `client_secret` as a form field alongside `client_id`, `code`, `code_verifier`, and `redirect_uri` (PKCE is still honored on top of the secret). The redirect URI is **fixed** in the OAuth App config — you cannot change it, so the manual listener-port trick doesn't apply; the user just lets the browser fail to connect on that port and pastes the address-bar URL back.\r\n\r\n## What NOT to do\r\n\r\n- **Don't use `mcp-remote` as a fallback.** It runs an npx subprocess whose OAuth callback server ALSO sits on the remote container's localhost — same problem. `mcp-remote` only helps when the MCP client doesn't speak remote HTTP at all (Hermes does natively).\r\n- **Don't push \"paste your API token and I'll add headers\"** if the user explicitly asked for OAuth. Offer the static-token shortcut only after explaining why the native OAuth flow fails in remote deployments. Respect the user's choice to do the extra legwork for rotation-free, scope-limited access.\r\n- **Don't claim Hermes doesn't support a feature without reading the source.** Grep the source tree before making capability claims.\r\n\r\n## Quick Reference Files\r\n\r\n- `scripts\u002Fdiagnose-oauth-mcp.py` — re-runnable, read-only-by-default diagnostic. Given a server name, it smoke-tests the stored access_token, attempts a refresh, smoke-tests the new token, and prints exactly which recovery branch you're in (`TOKEN_OK` = breaker\u002Frestart, `REFRESH_FIXED` = persist+restart, `SESSION_REVOKED` = full re-auth, `REFRESH_DEAD` = full re-auth\u002FAPI key). Pass `--write` to persist a working refreshed token atomically. Never prints secret values. **Run this FIRST when an OAuth MCP server reports \"not connected\"** — it encodes the pitfall 7\u002F9\u002F10 decision tree.\r\n- `references\u002Fstripe-mcp-oauth-revocation.md` — a worked example (Stripe) of a provider that revokes its OAuth session on a recurring basis, and the durable fix: switch to a static restricted API key.\r\n\r\n## Related\r\n\r\n- `native-mcp` — general guide to configuring MCP in Hermes. Authoritative config reference lives there.\r\n- `mcporter` — the external CLI bridge, for ad-hoc MCP calls outside of Hermes' config.\r\n","# MCP OAuth on a Remote Hermes Gateway\r\n\r\n## Overview\r\n\r\nHermes' built-in MCP OAuth client runs a one-shot HTTP listener on `127.0.0.1:\u003Cport>`\r\ninside the Hermes process and registers that loopback address as the OAuth\r\n`redirect_uri`. That works perfectly for a local CLI on the user's own machine.\r\nIt breaks completely when Hermes runs as a remote gateway (container, VPS,\r\nmessaging bot), because the user's browser resolves `127.0.0.1` to the user's own\r\nlaptop, not the remote container — so the authorization code never reaches Hermes.\r\n\r\nThis skill does the OAuth dance by hand and writes the resulting tokens into the\r\nexact files Hermes' token storage expects, so a subsequent `\u002Freload-mcp` finds\r\ncached tokens and skips the browser flow entirely.\r\n\r\n## When to Use\r\n\r\nUse this skill when **all** of the following are true:\r\n\r\n1. The user wants to add a remote HTTP MCP server that requires OAuth (not a static Bearer token).\r\n2. Hermes is running as a **remote gateway** (container, VPS, Docker, managed service) — NOT a local CLI on the user's laptop.\r\n3. The server supports OAuth 2.1 with PKCE and RFC 7591 Dynamic Client Registration (most modern MCP servers do — Better Stack, Linear, Cloudflare, Datadog, etc.). If it doesn't support DCR (GitHub is the notable exception), this skill does not apply — use a pre-registered OAuth App or a Personal Access Token instead.\r\n\r\nDo NOT use this for:\r\n- **Local CLI Hermes** — just set `auth: oauth` in `mcp_servers.\u003Cname>` and `\u002Freload-mcp`. The built-in flow opens a browser and captures the callback on localhost. Works perfectly.\r\n- **Servers that accept a static Bearer token (API key)** — always prefer `headers.Authorization: \"Bearer \u003Ctoken>\"` when the user is willing. Simpler, no refresh dance.\r\n- **GitHub Copilot MCP** (`api.githubcopilot.com\u002Fmcp\u002F`) — GitHub does not expose DCR. Use a PAT or a pre-registered OAuth App (see pitfall 12).\r\n\r\n## Why the Built-in OAuth Flow Fails on a Remote Gateway\r\n\r\nHermes' native MCP OAuth client (`tools\u002Fmcp_oauth.py`):\r\n\r\n1. Picks a free local port `P`.\r\n2. Registers a dynamic OAuth client with the AS, sending `redirect_uri = http:\u002F\u002F127.0.0.1:P\u002Fcallback`.\r\n3. Starts an HTTP server on `127.0.0.1:P` **inside the Hermes process**.\r\n4. Prints the authorize URL and waits for the code at its local endpoint.\r\n\r\nWhen Hermes runs remotely, the `127.0.0.1` in the `redirect_uri` is the remote\r\ncontainer's loopback, not the user's. After authorizing, the user's browser 302s\r\nto `http:\u002F\u002F127.0.0.1:P\u002Fcallback?code=...`, which resolves to the user's own\r\nlaptop and fails to connect. The callback never reaches the Hermes process, the\r\nflow times out, and `\u002Freload-mcp` returns \"No MCP tools available\" with no detail.\r\n\r\nSymptoms to recognize: `[xdg-open] \u003Cdefunct>` processes under the hermes user, an\r\nempty or missing tokens directory (`$HERMES_HOME\u002Fmcp-tokens\u002F`), and a reload that\r\nresponds without any \"Added\u002FReconnected: X\" line in `change_detail`.\r\n\r\n## Cheap First Fallbacks: the Built-in Flow's Own Escape Hatches\r\n\r\nBefore any manual token surgery, check whether the built-in flow's fallbacks\r\nalready cover the deployment. When Hermes detects a remote session it prints two\r\noptions alongside the authorize URL (`tools\u002Fmcp_oauth.py`):\r\n\r\n1. **Paste-back** — on an interactive TTY, a stdin reader races the HTTP\r\n   listener. The user authorizes, the browser fails to connect to\r\n   `127.0.0.1:\u003Cport>`, and they paste the full address-bar URL\r\n   (`?code=...&state=...`) back at the prompt. Works for SSH'd-in CLI sessions.\r\n2. **SSH port-forward** — `ssh -N -L \u003Cport>:127.0.0.1:\u003Cport> \u003Cuser>@\u003Chost>`\r\n   makes the redirect reach the remote listener normally.\r\n\r\nBoth require an interactive terminal to the Hermes host. The rest of this skill\r\nis for when there is NO interactive TTY — Hermes running purely as a messaging\r\ngateway\u002Fbot where `\u002Freload-mcp` triggers the flow with nobody at a prompt.\r\n\r\n## Preferred Front Door: the Hermes Dashboard (try this BEFORE manual token surgery)\r\n\r\nA remote Hermes gateway often also runs the **dashboard** web UI as a SEPARATE\r\nprocess (e.g. `hermes dashboard --host 0.0.0.0 --port \u003Cport>`; check with\r\n`ps aux | grep 'hermes dashboard'`). It exposes a connector\u002FMCP console —\r\nendpoints like `\u002Fapi\u002Fmcp\u002Fservers`, `\u002Fapi\u002Fmcp\u002Fstatus`, and `\u002Fconnectors` (all\r\nlogin-gated; a cookieless curl returning 401\u002F302 confirms they exist).\r\n\r\n**Why the dashboard solves the core problem:** when the user drives OAuth from\r\nthe dashboard *in their own browser*, the redirect lands in a context the\r\ndashboard can capture — sidestepping the `127.0.0.1`-callback failure that breaks\r\nthe CLI\u002Fmanual flow. So the correct escalation order for \"add or re-auth an OAuth\r\nMCP server on a remote gateway\" is:\r\n\r\n1. **Dashboard, in the user's browser** — the intended front door. Add servers, run OAuth, reload, all authenticated as the user. No copy-paste-callback dance, no hand-writing token files.\r\n2. **Manual token surgery (the rest of this skill)** — the FALLBACK for when there's no browser session to the dashboard (pure-chat\u002Fheadless context).\r\n\r\n**Finding the dashboard's PUBLIC URL.** The dashboard binds internally to\r\n`0.0.0.0:\u003Cport>`, but the user needs the externally-reachable URL. Most deploy\r\nplatforms inject it into the environment — grep for it rather than making the\r\nuser hunt:\r\n\r\n```bash\r\nenv | grep -iE \"HERMES_DASHBOARD_PUBLIC_URL|RAILWAY_PUBLIC_DOMAIN|RAILWAY_STATIC_URL|RAILWAY_SERVICE_.*_URL|PUBLIC_URL|BASE_URL|DOMAIN\" \\\r\n  | sed -E 's\u002F(TOKEN|SECRET|KEY|PASSWORD)=.*\u002F\\1=***REDACTED***\u002FI'\r\n```\r\n\r\n`HERMES_DASHBOARD_PUBLIC_URL` is authoritative when present. On Railway also check\r\n`RAILWAY_PUBLIC_DOMAIN` \u002F `RAILWAY_STATIC_URL` (the `*.up.railway.app` host) and\r\n`RAILWAY_SERVICE_*_URL` vars, which sometimes carry a friendlier custom domain.\r\nHand the user the full `https:\u002F\u002F` URL and point them at the Connectors\u002FMCP\r\nsection. ALWAYS pipe through the `sed` redaction above — these env greps sit next\r\nto `*_TOKEN`\u002F`*_SECRET` vars.\r\n\r\n**What the dashboard does NOT fix (still host-side \u002F shell):** stdio servers that\r\nneed shell auth state (a CLI `login` command whose credentials may not persist\r\nacross restarts) and anything reading credentials from `$HERMES_HOME\u002F.env`. Those\r\nare out of the dashboard's scope regardless.\r\n\r\n## The Workaround\r\n\r\nDo the OAuth dance manually, then write the resulting tokens into the exact files\r\nHermes' `HermesTokenStorage` would have written, so on `\u002Freload-mcp` Hermes finds\r\ncached tokens and skips the browser flow entirely.\r\n\r\nRun the shell commands below through the `terminal` tool on the gateway host and\r\ndo the Python steps (PKCE generation, token exchange, file writes) via\r\n`execute_code` or a `terminal` python3 invocation — file writes must happen in\r\nthe SAME code block as the token exchange (see pitfall 16).\r\n\r\n### 1. Confirm it's a remote gateway\r\n\r\n```bash\r\nenv | grep -iE \"HERMES|RAILWAY|CONTAINER\"\r\necho \"$DISPLAY $WAYLAND_DISPLAY $SSH_CLIENT\"\r\n```\r\n\r\nNo display + a remote indicator = remote gateway. `tools\u002Fmcp_oauth.py::_can_open_browser()`\r\nuses these same env vars, so if Hermes' own auto-detect says \"headless\", the\r\nbuilt-in flow won't work.\r\n\r\n### 2. Find HERMES_HOME and the config path\r\n\r\n```bash\r\nHERMES_HOME=$(python3 -c 'from hermes_constants import get_hermes_home; print(get_hermes_home())')\r\necho \"config: $HERMES_HOME\u002Fconfig.yaml\"\r\necho \"tokens: $HERMES_HOME\u002Fmcp-tokens\u002F\"\r\n```\r\n\r\n### 3. Discover OAuth metadata from the MCP server\r\n\r\nMCP servers advertise their OAuth setup via RFC 9728 (OAuth 2.0 Protected\r\nResource Metadata). The `WWW-Authenticate` header on a 401 tells you where to look:\r\n\r\n```bash\r\ncurl -sI https:\u002F\u002Fmcp.example.com | grep -i www-authenticate\r\n# → Bearer realm=\"mcp\", resource_metadata=\"https:\u002F\u002Fmcp.example.com\u002F.well-known\u002Foauth-protected-resource\"\r\n```\r\n\r\n**Not every server returns `WWW-Authenticate`.** Some return a bare\r\n`{\"errors\":[\"Unauthorized\"]}` 401 with no auth-discovery hint. When that happens,\r\nprobe well-known paths directly:\r\n\r\n```bash\r\nfor p in \\\r\n  \u002F.well-known\u002Foauth-protected-resource \\\r\n  \u002F.well-known\u002Foauth-authorization-server \\\r\n  \u002F.well-known\u002Fopenid-configuration ; do\r\n  echo \"=== $p ===\"\r\n  curl -s -A \"python-httpx\u002F0.27\" \"https:\u002F\u002Fmcp.example.com$p\" | head -c 400; echo\r\ndone\r\n```\r\n\r\nFetch the resource metadata to get `authorization_servers`, then fetch the AS's\r\n`\u002F.well-known\u002Foauth-authorization-server` to get `authorization_endpoint`,\r\n`token_endpoint`, and `registration_endpoint`.\r\n\r\nPitfall: many servers sit behind Cloudflare and 403 bare `urllib` user agents.\r\nAlways set `User-Agent: python-httpx\u002F0.27` (or similar) on requests in this flow.\r\n\r\n### 4. Dynamic Client Registration (RFC 7591)\r\n\r\nPOST to the `registration_endpoint` with:\r\n\r\n```json\r\n{\r\n  \"client_name\": \"Hermes Agent (manual OAuth)\",\r\n  \"redirect_uris\": [\"http:\u002F\u002F127.0.0.1:8765\u002Fcallback\"],\r\n  \"grant_types\": [\"authorization_code\", \"refresh_token\"],\r\n  \"response_types\": [\"code\"],\r\n  \"token_endpoint_auth_method\": \"none\",\r\n  \"scope\": \"\u003Cscopes_from_resource_metadata>\"\r\n}\r\n```\r\n\r\nOmit `scope` entirely if the AS's `scopes_supported` is empty — see step 5\r\npitfall. Use port `8765` (or any port — nothing will listen).\r\n`token_endpoint_auth_method: none` marks this as a public PKCE client. Save the\r\nreturned `client_id`.\r\n\r\n### 5. Build the authorize URL with PKCE\r\n\r\nGenerate:\r\n- `code_verifier`: `secrets.token_urlsafe(64)[:128]`\r\n- `code_challenge`: `base64url(sha256(code_verifier))` (no padding)\r\n- `state`: `secrets.token_urlsafe(24)`\r\n\r\nQuery params: `response_type=code`, `client_id`, `redirect_uri`, `code_challenge`,\r\n`code_challenge_method=S256`, `state`, plus `resource=\u003Cmcp_server_url>` (RFC 8707 —\r\nmany servers require this to bind the token to the specific MCP resource). Include\r\n`scope=\u003Cspace-separated>` ONLY if the AS metadata's `scopes_supported` is a\r\nnon-empty array AND\u002FOR the resource metadata declares specific scopes. If\r\n`scopes_supported: []`, omit the `scope` parameter — the server grants its full\r\ndefault set on its own. Fabricating scope strings against an empty\r\n`scopes_supported` can cause `invalid_scope` errors on some ASes.\r\n\r\n**Stash `code_verifier` and `state` to disk** (e.g. `\u002Ftmp\u002F.mcp-oauth-work\u002F\u003Cserver>.json`,\r\n0600 perms). You need them for step 7, possibly across multiple chat turns.\r\n\r\n### 6. Give the user the authorize URL\r\n\r\n```\r\nOpen this URL in your browser:\r\n\u003Cauthorize_url>\r\n\r\nAfter approving, your browser will try to load http:\u002F\u002F127.0.0.1:8765\u002Fcallback\r\nand fail to connect — THAT'S EXPECTED. Just copy the entire URL from the\r\naddress bar (it will contain ?code=...&state=...) and paste it back here.\r\n```\r\n\r\n### 7. Exchange the code for tokens\r\n\r\nWhen the user pastes the callback URL:\r\n\r\n1. Parse `code` and `state` from the query string.\r\n2. **Verify `state` matches the stashed value** (CSRF check — do not skip).\r\n3. POST `application\u002Fx-www-form-urlencoded` to the `token_endpoint`:\r\n   - `grant_type=authorization_code`\r\n   - `code=\u003Cfrom callback>`\r\n   - `redirect_uri=\u003Csame as step 4>`\r\n   - `client_id=\u003Cfrom step 4>`\r\n   - `code_verifier=\u003Cstashed>`\r\n   - `resource=\u003Cmcp_server_url>` (if the AS required it in step 5, include here too)\r\n4. Response contains `access_token`, `refresh_token`, `token_type`, `expires_in`, `scope`.\r\n\r\n### 8. Write tokens in Hermes' exact schema\r\n\r\n`tools\u002Fmcp_oauth.py::HermesTokenStorage` expects two files under\r\n`$HERMES_HOME\u002Fmcp-tokens\u002F` (create dir with `0o700`, files with `0o600`):\r\n\r\n**`\u003Cserver_name>.json`** — the `OAuthToken` pydantic model:\r\n```json\r\n{\r\n  \"access_token\": \"...\",\r\n  \"token_type\": \"Bearer\",\r\n  \"expires_in\": 7200,\r\n  \"refresh_token\": \"...\",\r\n  \"scope\": \"read write\"\r\n}\r\n```\r\n\r\n**`\u003Cserver_name>.client.json`** — the `OAuthClientInformationFull` model:\r\n```json\r\n{\r\n  \"client_id\": \"...\",\r\n  \"redirect_uris\": [\"http:\u002F\u002F127.0.0.1:8765\u002Fcallback\"],\r\n  \"grant_types\": [\"authorization_code\", \"refresh_token\"],\r\n  \"response_types\": [\"code\"],\r\n  \"token_endpoint_auth_method\": \"none\",\r\n  \"scope\": \"read write\",\r\n  \"client_name\": \"...\"\r\n}\r\n```\r\n\r\nWrite each file via `json.dumps(..., indent=2)`. Sanitize the filename with\r\n`re.sub(r'[^\\w\\-]', '_', server_name)[:128]` — this matches `_safe_filename()` in\r\nHermes' token storage.\r\n\r\n### 9. Add the server to config.yaml\r\n\r\n```yaml\r\nmcp_servers:\r\n  \u003Cname>:\r\n    url: \"https:\u002F\u002Fmcp.example.com\"\r\n    auth: oauth\r\n    timeout: 180\r\n    connect_timeout: 60\r\n```\r\n\r\n### 10. Smoke-test the token BEFORE asking the user to reload\r\n\r\nManually POST an MCP `initialize` request to confirm the token works end-to-end —\r\nthis catches scope misconfigurations, wrong `resource` values, and CF blocks\r\nbefore the user is confused by another \"No MCP tools available\" reload:\r\n\r\n```python\r\nbody = json.dumps({\r\n    \"jsonrpc\": \"2.0\", \"id\": 1, \"method\": \"initialize\",\r\n    \"params\": {\r\n        \"protocolVersion\": \"2025-06-18\",\r\n        \"capabilities\": {},\r\n        \"clientInfo\": {\"name\": \"hermes-debug\", \"version\": \"1.0\"},\r\n    },\r\n}).encode()\r\n# POST to the MCP URL with:\r\n#   Authorization: Bearer \u003Caccess_token>\r\n#   Accept: application\u002Fjson, text\u002Fevent-stream\r\n#   Content-Type: application\u002Fjson\r\n#   MCP-Protocol-Version: 2025-06-18\r\n#   User-Agent: python-httpx\u002F0.27\r\n```\r\n\r\nExpect HTTP 200 with `Content-Type: text\u002Fevent-stream` and a JSON-RPC result\r\ncontaining `serverInfo` and `capabilities`. **Do not use `urllib` with its default\r\nUA** — Cloudflare will 403 you even though Hermes (which uses httpx) will succeed.\r\n`scripts\u002Fdiagnose-oauth-mcp.py` automates this smoke test.\r\n\r\n### 11. Tell the user to run `\u002Freload-mcp`\r\n\r\nOn reload, Hermes sees `auth: oauth`, calls `HermesTokenStorage.get_tokens()`,\r\nfinds your cached tokens, skips the browser flow, and registers `mcp_\u003Cname>_*`\r\ntools. Refresh happens automatically before `expires_in` elapses.\r\n\r\n## Pitfalls & Lessons Learned\r\n\r\n1. **Do not assume \"headless\" means \"OAuth impossible.\"** The built-in flow works fine for local CLI; the issue is strictly remote deployments where the user's browser and the Hermes process are on different machines. Check the execution environment before claiming OAuth isn't an option.\r\n\r\n2. **Read the source, not just the skill docs.** `tools\u002Fmcp_oauth.py` and the MCP config reference in `website\u002Fdocs\u002F` are the authoritative references. Grep the tree before telling the user a feature \"doesn't exist.\"\r\n\r\n3. **Cloudflare UA filter.** Many MCP\u002FOAuth providers front their infra with Cloudflare, which 403s `python-urllib\u002F*` user agents on metadata endpoints even though those endpoints are public. Set `User-Agent: python-httpx\u002F0.27` (or any browser-like string) on every request in this flow. Hermes itself uses httpx, so this is never a problem in the real connection path.\r\n\r\n4. **Include `resource` in both authorize and token requests.** RFC 8707 resource indicators are not optional for most modern MCP servers — they bind the issued token to the specific MCP resource URL. Leaving it out sometimes still works but may yield a token that later fails at the MCP server with a scope\u002Faudience error.\r\n\r\n5. **Trailing slash matters.** Some servers advertise the resource as `https:\u002F\u002Fmcp.example.com\u002F` with a trailing slash and reject tokens issued against the no-slash variant. Copy the `resource` value verbatim from the `.well-known\u002Foauth-protected-resource` response.\r\n\r\n6. **`\u002Freload-mcp` is silent on failure.** If the reload shows \"No MCP tools available\" with no `change_detail` line, a server is in config but failed to connect and no error bubbled up. Tail the error log, smoke-test the token directly with a manual `initialize` POST, and — if everything looks good — ask for a full process restart.\r\n\r\n7. **Circuit breaker can survive `\u002Freload-mcp`.** `tools\u002Fmcp_tool.py` keeps a module-level error-count dict with a small threshold. Once tripped (e.g. after token expiry produces several consecutive failures), the tool handler can short-circuit before calling the server, so no successful call resets the counter. Symptom: reload says \"Reconnected: X\" but subsequent calls still fail with \"server unreachable\" in the same conversation. Recovery order: try `\u002Freload-mcp` FIRST (cheap, no chat-process blip) — on current builds it can clear the counter; only escalate to a full gateway process restart if a live call STILL short-circuits after reload. Do not lead with \"you must restart.\"\r\n\r\n8. **Refresh on an expired access_token + a tripped breaker is a deadlock.** The auto-refresh logic runs inside the MCP call path, which the breaker short-circuits once tripped. Manually refreshing the token on disk does not help by itself — pair a manual token refresh with a full restart, not a `\u002Freload-mcp`.\r\n\r\n9. **`invalid_grant` on a manual refresh means the refresh token is DEAD — re-auth is the only fix, do not loop.** When the access_token has been expired long enough, the refresh_token can also be revoked\u002Fexpired server-side. A `grant_type=refresh_token` POST then returns HTTP 400 `{\"error\":\"invalid_grant\",...}` (wording varies: \"Grant not found\", \"Token expired\", \"refresh token is invalid\"). There is NO recovery from the gateway side. Hand back to the user with two options: (a) re-run the full manual OAuth dance (steps 3–10), or (b) if the provider offers a static personal API key, switch to that — no refresh\u002Fexpiry cycle, more durable for an unattended remote gateway. Detect early: before any create\u002Fupdate operation against an OAuth MCP, check `expires_at` vs `time.time()`; if already expired, attempt the refresh first and surface `invalid_grant` immediately rather than failing mid-task.\r\n\r\n10. **A successful refresh that STILL yields a rejected token = server-side SESSION revocation; only a fresh authorization_code flow fixes it.** Distinct from pitfall 9. The stored token file can look healthy (`expires_at` well out, refresh_token present), yet a live `initialize` POST returns `401 invalid_token` with a JSON-RPC body like `{\"error\":{\"code\":-32002,\"message\":\"Session expired. Please re-authenticate.\"}}`. The `grant_type=refresh_token` POST may **succeed** (HTTP 200, new access_token) — yet the brand-new token gets the SAME `-32002`. The provider revoked the underlying MCP *session* server-side; the OAuth refresh chain re-mints credentials but cannot re-establish a revoked session. Decision rule when an OAuth MCP reports \"not connected\": (1) smoke-test the stored access_token with a manual `initialize` POST; (2) if `401 invalid_token`, attempt a refresh and smoke-test the NEW token; (3a) new token works → write it + restart to clear the breaker; (3b) new token STILL gets `-32002`\u002F\"Session expired\" → stop, this is session revocation, hand the user the authorize URL for a full re-auth. `scripts\u002Fdiagnose-oauth-mcp.py` automates steps 1–2 and prints which branch you're in. For an unattended gateway whose session keeps getting revoked, prefer a static Personal API key. See `references\u002Fstripe-mcp-oauth-revocation.md` for a worked example of a provider that revokes weekly.\r\n\r\n11. **Client info file is NOT optional.** Hermes needs `\u003Cserver>.client.json` to know the `client_id` for refresh grants. Skipping it means the first refresh fails and the user has to re-auth — writing both files is the whole point of this skill.\r\n\r\n12. **Never hand-type the redirect URL for the user to open.** Generate the authorize URL programmatically with `urllib.parse.urlencode()`. Spaces in scopes and special chars in `state` break string-concatenated URLs.\r\n\r\n13. **Security: the stash file contains the `code_verifier`.** Delete `\u002Ftmp\u002F.mcp-oauth-work\u002F\u003Cserver>.json` immediately after successful token exchange. There's no reason to keep a proof-of-identity secret around once it's consumed.\r\n\r\n14. **Write what the token endpoint actually returned.** The AS may grant a narrower (or wider) scope than requested. Write the `scope` from the token-exchange response to `\u003Cserver>.json`, not what you asked for in step 5. When `scopes_supported: []`, the explicit scope list you send IS authoritative both ways: some servers grant exactly what you list (pass narrow scopes for least-privilege, or enumerate the full set if the user needs everything), and some won't echo the granted scope back at registration time — only the token-exchange response is authoritative.\r\n\r\n15. **OAuth tokens often double as Bearer tokens against the provider's public REST API.** The access_token in `\u003Cserver>.json` is frequently not \"MCP-only\" — `Authorization: Bearer \u003Ctoken>` against the provider's documented REST API succeeds whenever the corresponding resource scope was granted. This is the OAuth 2.0 spec, not a provider quirk. When the MCP server is read-only but you need a write operation, check whether the OAuth token can hit the provider's REST API directly before suggesting a separate API key.\r\n\r\n16. **Secret redaction can mask tokens in tool output.** If secret redaction is enabled, tokens and long opaque strings render as `***` in tool-result output, so you cannot `print(response)` to keep the access_token visible across turns. Combined with single-use `code` values from authorization_code grants: if you print the token-exchange response, you may lose the token AND consume the code, forcing a restart with a fresh authorize URL. **Always write the access_token directly to its final destination file in the SAME code block that performs the token exchange.** If you must print for debugging, print only `len(access_token)`, `token_type`, `scope`, `expires_in` — never the secret.\r\n\r\n17. **GitHub MCP (`api.githubcopilot.com\u002Fmcp\u002F`) uses a pre-registered confidential OAuth App, not DCR + PKCE-public.** Its client info ships with a real `client_secret` and `token_endpoint_auth_method: client_secret_post`. The token-exchange POST to `https:\u002F\u002Fgithub.com\u002Flogin\u002Foauth\u002Faccess_token` must include `client_secret` as a form field alongside `client_id`, `code`, `code_verifier`, and `redirect_uri` (PKCE is still honored on top of the secret). The redirect URI is **fixed** in the OAuth App config — you cannot change it, so the manual listener-port trick doesn't apply; the user just lets the browser fail to connect on that port and pastes the address-bar URL back.\r\n\r\n## What NOT to do\r\n\r\n- **Don't use `mcp-remote` as a fallback.** It runs an npx subprocess whose OAuth callback server ALSO sits on the remote container's localhost — same problem. `mcp-remote` only helps when the MCP client doesn't speak remote HTTP at all (Hermes does natively).\r\n- **Don't push \"paste your API token and I'll add headers\"** if the user explicitly asked for OAuth. Offer the static-token shortcut only after explaining why the native OAuth flow fails in remote deployments. Respect the user's choice to do the extra legwork for rotation-free, scope-limited access.\r\n- **Don't claim Hermes doesn't support a feature without reading the source.** Grep the source tree before making capability claims.\r\n\r\n## Quick Reference Files\r\n\r\n- `scripts\u002Fdiagnose-oauth-mcp.py` — re-runnable, read-only-by-default diagnostic. Given a server name, it smoke-tests the stored access_token, attempts a refresh, smoke-tests the new token, and prints exactly which recovery branch you're in (`TOKEN_OK` = breaker\u002Frestart, `REFRESH_FIXED` = persist+restart, `SESSION_REVOKED` = full re-auth, `REFRESH_DEAD` = full re-auth\u002FAPI key). Pass `--write` to persist a working refreshed token atomically. Never prints secret values. **Run this FIRST when an OAuth MCP server reports \"not connected\"** — it encodes the pitfall 7\u002F9\u002F10 decision tree.\r\n- `references\u002Fstripe-mcp-oauth-revocation.md` — a worked example (Stripe) of a provider that revokes its OAuth session on a recurring basis, and the durable fix: switch to a static restricted API key.\r\n\r\n## Related\r\n\r\n- `native-mcp` — general guide to configuring MCP in Hermes. Authoritative config reference lives there.\r\n- `mcporter` — the external CLI bridge, for ad-hoc MCP calls outside of Hermes' config.\r\n",{"name":5,"author":42,"license":15,"version":43,"metadata":44,"platforms":51,"description":7},"Ben Barclay (benbarclay), Hermes Agent","1.0.0",{"hermes":45},{"tags":46,"related_skills":49},[22,19,47,48],"PKCE","Remote-Deployment",[50,33,24],"native-mcp",[28,36],"main","0d1434f89f4bc6b07e9d272accd8c1013768820f","archive\u002Fskill-md-reviewed\u002Fsha256\u002Faf\u002Faff327983c8e5798762c0281c1de146d97e15d12129878435540bf539346c506",0,"https:\u002F\u002Fgithub.com\u002Fzapabob\u002FSkills","https:\u002F\u002Fgithub.com\u002Fzapabob","The Open University of JAPAN　2019-now\r\n\r\nTokyo University of Science　2007-2010","2026-10-26 16:29:01",{"source":8,"skillName":5,"commands":61,"prompt":71,"zipAvailable":72},[62,65,68],{"tool":63,"command":64},"npx","npx skills add zapabob\u002FSkills --skill mcp-oauth-remote-gateway",{"tool":66,"command":67},"bunx","bunx skills add zapabob\u002FSkills --skill mcp-oauth-remote-gateway",{"tool":69,"command":70},"pnpm","pnpm dlx skills add zapabob\u002FSkills --skill mcp-oauth-remote-gateway","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fzapabob\u002FSkills\u002Fblob\u002Fmain\u002Farchive\u002Fskill-md-reviewed\u002Fsha256\u002Faf\u002Faff327983c8e5798762c0281c1de146d97e15d12129878435540bf539346c506\u002FSKILL.md",true,[],[75,96,120,144,168,184],{"skillNo":76,"name":77,"nameZh":6,"description":78,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":37},"01M6GJTE1GESGGF9K028Y7753E","xurl","X\u002FTwitter via xurl CLI: post, search, DM, media, v2 API.","https:\u002F\u002Fgithub.com\u002Fzapabob\u002FSkills\u002Fblob\u002Fmain\u002Fregistry\u002Fskills\u002Fxurl\u002Fvariants\u002Fhermes-agent\u002FSKILL.md",[],[77,82,36,83,84,28,85,86,87,88,89,90,91,30,31,92,52,93,94,95],"openclaw","cli","github","windows","official","search","https","social-media","api","Media","twitter","social","via","post",{"skillNo":97,"name":98,"nameZh":6,"description":99,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":100,"categories":101,"keywords":102,"publishedAt":37},"01M6GJT8S1PXQ8WPXT1HSNBWH2","writing-plans","Write implementation plans: bite-sized tasks, paths, code.","https:\u002F\u002Fgithub.com\u002Fzapabob\u002FSkills\u002Fblob\u002Fmain\u002Fregistry\u002Fskills\u002Fwriting-plans\u002Fvariants\u002Fhermes-agent\u002FSKILL.md",[],[103,104,105,106,36,107,28,108,85,109,110,111,112,113,114,115,116,117,118,119],"writing","writing plans","plans","design","review","workflow","documentation","tasks","development","code","planning","code-review","subagent","write","superpowers","paths","test-driven-development",{"skillNo":121,"name":122,"nameZh":6,"description":123,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":124,"categories":125,"keywords":126,"publishedAt":37},"01M6GJST0H5X7WHBJ3BZK0DVKH","whisper","OpenAI's general-purpose speech recognition model. Supports 99 languages, transcription, translation to English, and language identification. Six model sizes from tiny (39M params) to large (1550M params). Use for speech-to-text, podcast transcription, or multilingual audio processing. Best for robust, multilingual ASR.","https:\u002F\u002Fgithub.com\u002Fzapabob\u002FSkills\u002Fblob\u002Fmain\u002Fregistry\u002Fskills\u002Fwhisper\u002Fvariants\u002Fhermes-agent-optional\u002FSKILL.md",[],[122,36,28,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143],"openai","speech","multimodal","Transformers","ASR","Audio","text","model","speech recognition","use","general","multilingual","translation","english","identification","processing","Audio Processing",{"skillNo":145,"name":146,"nameZh":6,"description":147,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":148,"categories":149,"keywords":150,"publishedAt":37},"01M6GJSMRQ8EETZTYMG72P70EA","weights-and-biases","W&B: log ML experiments, sweeps, model registry, dashboards.","https:\u002F\u002Fgithub.com\u002Fzapabob\u002FSkills\u002Fblob\u002Fmain\u002Fregistry\u002Fskills\u002Fweights-and-biases\u002Fvariants\u002Fhermes-agent\u002FSKILL.md",[],[151,36,152,153,85,154,155,156,157,158,159,134,160,161,162,163,164,165,166,167],"weights and biases","tensorflow","experiments","pytorch","visualization","registry","real-time","tuning","dashboards","experiment","log","time","Experiment Tracking","Model Registry","Hyperparameter Tuning","WandB","Real-Time Visualization",{"skillNo":169,"name":170,"nameZh":6,"description":171,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":172,"categories":173,"keywords":174,"publishedAt":37},"01M6GJS19KDPRY112JTR326S06","watchers","Poll RSS, JSON APIs, and GitHub with watermark dedup.","https:\u002F\u002Fgithub.com\u002Fzapabob\u002FSkills\u002Fblob\u002Fmain\u002Fregistry\u002Fskills\u002Fwatchers\u002Fvariants\u002Fhermes-agent-optional\u002FSKILL.md",[],[170,36,175,84,28,176,177,178,179,180,181,30,31,182,183],"terminal","automation","http","monitoring","cron","json","rss","devops","with",{"skillNo":185,"name":186,"nameZh":6,"description":187,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":188,"categories":189,"keywords":190,"publishedAt":37},"01M6GJRHJD2A6Q830SWF9W48BC","serving-llms-vllm","vLLM: high-throughput LLM serving, OpenAI API, quantization.","https:\u002F\u002Fgithub.com\u002Fzapabob\u002FSkills\u002Fblob\u002Fmain\u002Fregistry\u002Fskills\u002Fvllm\u002Fvariants\u002Fhermes-agent\u002FSKILL.md",[],[191,192,193,28,194,127,195,196,197,130,198,90,199,200,201,202,203,204,205,206],"llms","vLLM","serving llms vllm","research","openai api","tensor","Inference Serving","Production","llm serving","High Throughput","PagedAttention","Continuous Batching","Quantization","Tensor Parallelism","high-throughput","throughput"]