|
| 1 | +# Portions of this package are derived from MCPCat/mcpcat-typescript-sdk |
| 2 | +# Copyright (c) 2025 MCPcat |
| 3 | +# Licensed under the MIT License: https://github.com/MCPCat/mcpcat-typescript-sdk/blob/main/LICENSE |
| 4 | + |
| 5 | +"""Read HTTP request headers inside a host callback, on either MCP SDK major. |
| 6 | +
|
| 7 | +``identify``, ``intent_fallback``, ``event_properties`` and ``before_send`` |
| 8 | +receive the SDK's own per-request context under ``extra["ctx"]``, unchanged. We |
| 9 | +deliberately do not synthesise a uniform shape for it: the two majors expose |
| 10 | +different objects, and a fabricated one is a convincing partial lie about a |
| 11 | +shape the SDK actually changed. Headers are the one thing nearly every callback |
| 12 | +wants, so they get a helper instead:: |
| 13 | +
|
| 14 | + from posthog.mcp import get_request_headers |
| 15 | +
|
| 16 | + def identify(request, extra): |
| 17 | + headers = get_request_headers(extra) or {} |
| 18 | + token = headers.get("authorization") |
| 19 | + ... |
| 20 | +
|
| 21 | +Returns ``None`` when the request did not arrive over HTTP — stdio and |
| 22 | +in-memory transports carry no headers at all. |
| 23 | +""" |
| 24 | + |
| 25 | +from __future__ import annotations |
| 26 | + |
| 27 | +from typing import Any, Dict, Optional |
| 28 | + |
| 29 | +__all__ = ["get_request_headers"] |
| 30 | + |
| 31 | +RequestHeaderBag = Dict[str, str] |
| 32 | + |
| 33 | + |
| 34 | +def get_request_headers(extra: Any) -> Optional[RequestHeaderBag]: |
| 35 | + """The request's HTTP headers as a plain dict with lowercase keys, or ``None``. |
| 36 | +
|
| 37 | + Accepts the ``extra`` dict handed to a callback, or the raw per-request |
| 38 | + context itself, so it works whichever one a host happens to hold. |
| 39 | + """ |
| 40 | + ctx = extra |
| 41 | + if isinstance(extra, dict): |
| 42 | + ctx = extra.get("ctx") |
| 43 | + if ctx is None: |
| 44 | + return None |
| 45 | + |
| 46 | + # Both majors reach the transport's request the same way from their own |
| 47 | + # context object (`ServerRequestContext` on 2.x, `RequestContext` on 1.x); |
| 48 | + # `request` is None on stdio. |
| 49 | + source = getattr(getattr(ctx, "request", None), "headers", None) |
| 50 | + if source is None: |
| 51 | + return None |
| 52 | + return _to_header_bag(source) |
| 53 | + |
| 54 | + |
| 55 | +def _to_header_bag(source: Any) -> Optional[RequestHeaderBag]: |
| 56 | + """Flatten a Starlette ``Headers``, a mapping, or anything iterable of pairs |
| 57 | + into a lowercase-keyed dict. Never raises: a header read must not take a |
| 58 | + tool call down with it.""" |
| 59 | + try: |
| 60 | + # Starlette's Headers and dict both expose .items(); Headers already |
| 61 | + # lowercases, a plain dict may not, so normalise either way. |
| 62 | + items = source.items() if hasattr(source, "items") else source |
| 63 | + bag: RequestHeaderBag = {} |
| 64 | + for key, value in items: |
| 65 | + if isinstance(key, str) and isinstance(value, str): |
| 66 | + bag[key.lower()] = value |
| 67 | + return bag |
| 68 | + except Exception: # noqa: BLE001 - best effort, never break the tool path |
| 69 | + return None |
0 commit comments