-
Notifications
You must be signed in to change notification settings - Fork 395
Open
Description
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
Labels
No labels