Skip to content

feat: enable tool access to HTTP request headers #175

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions crates/rmcp/src/handler/server/tool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,9 @@ impl<'service, S> ToolCallContext<'service, S> {
pub fn name(&self) -> &str {
&self.name
}
pub fn request_context(&self) -> &RequestContext<RoleServer> {
&self.request_context
}
}

pub trait FromToolCallContextPart<'a, S>: Sized {
Expand Down
5 changes: 3 additions & 2 deletions crates/rmcp/src/transport/sse_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::{collections::HashMap, io, net::SocketAddr, sync::Arc, time::Duration};
use axum::{
Json, Router,
extract::{Query, State},
http::{StatusCode, request::Parts},
http::{self, StatusCode, request::Parts},
response::{
Response,
sse::{Event, KeepAlive, Sse},
Expand Down Expand Up @@ -74,7 +74,8 @@ async fn post_event_handler(
.ok_or(StatusCode::NOT_FOUND)?
.clone()
};
message.insert_extension(parts);
let headers_to_insert: http::HeaderMap = parts.headers.clone();
message.insert_extension(headers_to_insert);
if tx.send(message).await.is_err() {
tracing::error!("send message error");
return Err(StatusCode::GONE);
Expand Down
6 changes: 3 additions & 3 deletions crates/rmcp/src/transport/streamable_http_server/axum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::{collections::HashMap, io, net::SocketAddr, sync::Arc, time::Duration};
use axum::{
Json, Router,
extract::State,
http::{HeaderMap, HeaderValue, StatusCode, request::Parts},
http::{self, HeaderMap, HeaderValue, StatusCode, request::Parts},
response::{
IntoResponse, Response,
sse::{Event, KeepAlive, Sse},
Expand Down Expand Up @@ -84,8 +84,8 @@ async fn post_handler(
.ok_or((StatusCode::NOT_FOUND, "session not found").into_response())?;
session.handle().clone()
};
// inject request part
message.insert_extension(parts);
let headers_to_insert: http::HeaderMap = parts.headers.clone();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I prefer to inject whole request part, in case of people want to get other information like request uri or other data in http::Extensions

message.insert_extension(headers_to_insert);
match &message {
ClientJsonRpcMessage::Request(_) | ClientJsonRpcMessage::BatchRequest(_) => {
let receiver = handle.establish_request_wise_channel().await.map_err(|e| {
Expand Down
14 changes: 13 additions & 1 deletion examples/servers/src/common/counter.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use std::sync::Arc;

use crate::common::extractor::ReqHeaders;
use rmcp::{
Error as McpError, RoleServer, ServerHandler, const_string, model::*, schemars,
service::RequestContext, tool,
};
use serde_json::json;
use tokio::sync::Mutex;

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct StructRequest {
pub a: i32,
Expand Down Expand Up @@ -81,6 +81,18 @@ impl Counter {
(a + b).to_string(),
)]))
}
#[tool(description = "Get the request headers")]
fn get_headers(&self, ReqHeaders(headers): ReqHeaders) -> Result<CallToolResult, McpError> {
let mut header_strings = Vec::new();
for (name, value) in headers.iter() {
if let Ok(value_str) = value.to_str() {
header_strings.push(format!("{}: {}", name, value_str));
}
}
Ok(CallToolResult::success(vec![Content::text(
header_strings.join("\n"),
)]))
}
}
const_string!(Echo = "echo");
#[tool(tool_box)]
Expand Down
20 changes: 20 additions & 0 deletions examples/servers/src/common/extractor.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
use axum::http::HeaderMap;
use rmcp::Error as McpError;
use rmcp::handler::server::tool::{FromToolCallContextPart, ToolCallContext};

#[derive(Debug)]
pub struct ReqHeaders(pub HeaderMap);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I prefer to use HttpReqHeaders or HttpRequestHeaders as its ident.


impl<'a, S> FromToolCallContextPart<'a, S> for ReqHeaders {
fn from_tool_call_context_part(
context: ToolCallContext<'a, S>,
) -> Result<(Self, ToolCallContext<'a, S>), McpError> {
match context.request_context().extensions.get::<HeaderMap>() {
Some(headers) => Ok((ReqHeaders(headers.clone()), context)),
None => Err(McpError::internal_error(
"HTTP headers not found in context.",
None,
)),
}
}
}
1 change: 1 addition & 0 deletions examples/servers/src/common/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub mod calculator;
pub mod counter;
pub mod extractor;
pub mod generic_service;
Loading