Context API

Access runtime MCP capabilities—logging, progress, resource access, sampling—inside any Hyperia tool, resource, or prompt.

When you decorate a Python function as a tool/resource/prompt, it executes inside an MCP request‑scope. Hyperia exposes that scope via the Context object so your code can talk back to the client, stream progress, or even call the client’s LLM.


What Is Context?

The object provides:

  • Logging – debug/info/warning/error back to the caller.

  • Progress reporting – live percentage updates for long tasks.

  • Resource access – read other resources on the server.

  • LLM sampling – let the client’s model generate text/images mid‑function.

  • Request meta – IDs, client origin, etc.

  • Advanced hooks – raw session objects and server instance when absolutely needed.


Injecting Context

Add a parameter typed Context anywhere in the signature. Hyperia will inject it.

from hyperia import Hyperia, Context

mcp = Hyperia("CtxDemo")

@mcp.tool()
async def process_file(uri: str, ctx: Context) -> str:
    await ctx.info(f"Processing {uri}")
    ...

Rules

  • Parameter name doesn’t matter; the type hint does.

  • Omit it if you don’t need context.

  • Most methods are async; declare your function async def.

  • Context only exists during a request; calling methods outside raises errors. For unit tests you can type‑hint Context | None = None.

Context in Resources & Prompts


Dependency Helper get_context()

If a deep utility function can’t accept an extra param, retrieve the active context dynamically (server‑side only):

Calling get_context() outside a request → RuntimeError.


Capabilities

1. Logging

Method
Use

ctx.debug(msg)

Verbose trace

ctx.info(msg)

Normal progress

ctx.warning(msg)

Non‑fatal issues

ctx.error(msg)

Errors

ctx.log(level, msg, logger_name=None)

Custom level/logger

2. Progress Reporting

Signature: ctx.report_progress(progress: float, total: float | None = None). Client must send a progressToken or updates are ignored.

3. Resource Access

Returns a list of ReadResourceContents; usually read content of first part.

4. LLM Sampling

Signature: ctx.sample(messages, system_prompt=None, temperature=None, max_tokens=None) → returns TextContent or ImageContent.

5. Request Info


Advanced Accessors

Also available: ctx.session, ctx.request_context for low‑level operations (use sparingly).

HTTP Request (Starlette) (Server builds with ASGI)

ctx.get_http_request() is deprecated → use hyperia.server.dependencies.get_http_request() inside ASGI stacks if needed.


Server Behaviour Flags

Duplicate Context Injection

Context itself does not have duplication rules, but note you can configure duplicate tools/resources/prompts via on_duplicate_* settings at server init as shown in earlier chapters.

Last updated