Skip to content

Question: Accessing Request Context in MCP Tool Handlers #504

@antoncxx

Description

@antoncxx

I’m building an MCP server and have an authentication middleware that validates a session token from the request headers.
Here’s the relevant middleware code:

pub async fn authentication_middleware(
    State(context): State<AppContext>,
    headers: HeaderMap,
    mut request: Request<axum::body::Body>,
    next: Next,
) -> Result<Response, StatusCode> {
    let session_token = extract_token(&headers).ok_or(StatusCode::UNAUTHORIZED)?;

    let db_token = get_db_token(&context)
        .await
        .ok_or(StatusCode::INTERNAL_SERVER_ERROR)?;

    let session = fetch_session_details(&context, db_token, &session_token)
        .await
        .ok_or(StatusCode::INTERNAL_SERVER_ERROR)?;

    if matches!(session.r#type, RemoteAccessType::Mcp) {
        request.extensions_mut().insert(session);
        Ok(next.run(request).await)
    } else {
        Err(StatusCode::BAD_REQUEST)
    }
}

The middleware works fine, but I need to access the session (inserted into the request extensions) inside my tool handler.
However, in all examples I’ve seen, tool handlers only receive their parameter schema, like this:

#[tool(description = "Execute a command on the client machine")]
async fn execute_command(
    &self,
    Parameters(ExecuteCommandParameters { command, arguments }): Parameters<ExecuteCommandParameters>,
) -> Result<CallToolResult, ErrorData> {
    // I need to access the session here
}

How can I access the session data (inserted in request extensions by middleware) from within a tool handler?
Is there a supported way to read per-request context or extensions from within a tool?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions