Skip to main content

McpServer

Struct McpServer 

Source
pub struct McpServer { /* private fields */ }
Expand description

Independently owned MCP server serving any concrete ToolsetBackend.

The server retains a shared reference to the caller’s toolset. Server shutdown never shuts down that toolset; the caller owns its cleanup separately. This example binds a real loopback endpoint and requires an available port. Keep the Tokio runtime driven until both server and toolset cleanup settle. Dropping the server or its shutdown observation signals its retained cleanup owner; only explicit toolset shutdown closes the separate executable source.

§Examples

use std::sync::Arc;
use tools_kit::{Toolset, ToolsetBackend, ToolHandlerBackend, ToolError};
use tools_kit::declaration::ToolName;
use tools_kit::execution::{ToolHandlerInput, ToolHandlerOutput, ToolInvocation};
use tools_kit::local::ToolRegistration;
use tools_kit::mcp::{McpServer, McpServerConfig, McpClientConfig, McpConnectionConfig};
// MCP requires object-shaped arguments; local typed tools may use scalars.
#[derive(serde::Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
struct DoubleArgs { value: i64 }
#[derive(serde::Serialize, schemars::JsonSchema)]
struct DoubleResult { value: i64 }
let config = McpServerConfig::new("127.0.0.1:8000".parse().unwrap(), "/mcp", "page")?;
let source = Arc::new(Toolset::local(vec![ToolRegistration::typed(
    "double", |input: DoubleArgs| async move {
        let value = input.value.checked_mul(2).ok_or(ToolError::InvalidArguments {
            tool: ToolName::new("double")?, message: "doubling would overflow i64".into(), issues: Vec::new(),
        })?;
        Ok(DoubleResult { value })
    },
)?])?);
let server = McpServer::start(Arc::clone(&source), config).await;
let observed = async { match server {
    Ok(server) => {
        let client_work = async {
            let client = Toolset::mcp(McpClientConfig::new(McpConnectionConfig::StreamableHttp {
                endpoint: "http://127.0.0.1:8000/mcp".parse().unwrap(), headers: Default::default(),
            })).await?;
            let invoked = async {
                let mut handler = client.tool_handler(ToolName::new("double")?).await?;
                let output = handler.step(ToolHandlerInput::Invoke(ToolInvocation {
                    call_id: Some("client-call".into()), arguments: serde_json::json!({"value":21}),
                })).await?;
                let ToolHandlerOutput::Completed(result) = output else {
                    return Err(ToolError::Protocol { message: "unexpected interaction".into() });
                };
                assert!(!result.is_error);
                assert_eq!(result.structured_content, Some(serde_json::json!({"value":42})));
                Ok::<(), ToolError>(())
            }.await;
            let client_closed = client.shutdown().await;
            if let Err(error) = &client_closed {
                eprintln!("Cleanup failed: {error}");
            }
            invoked?;
            client_closed
        }.await;
        let serving_closed = server.shutdown().await; // Consumes and joins serving.
        if let Err(error) = &serving_closed {
            eprintln!("Cleanup failed: {error}");
        }
        client_work?;
        serving_closed?;
        assert_eq!(source.list_tools().await?.len(), 1); // Source remains usable.
        Ok(())
    }
    Err(error) => Err(error),
}
}.await;
let source_closed = source.shutdown().await;
if let Err(error) = &source_closed {
    eprintln!("Cleanup failed: {error}");
}
observed?;
source_closed?;

Implementations§

Source§

impl McpServer

Source

pub async fn start<T: ToolsetBackend>( toolset: Arc<T>, config: McpServerConfig, ) -> Result<Self, ToolError>

Binds and starts the configured loopback endpoint eagerly.

A failed start leaves the caller’s toolset usable. Neither the toolset nor its associated handler needs to implement Clone or use supplied handles.

This example binds a real loopback endpoint and requires an available port. Keep the Tokio runtime driven through both independently owned cleanup operations.

See McpServer for the complete client/server/source cleanup sequence.

§Errors

Returns ToolError::InvalidConfiguration for invalid server settings or ToolError::Transport when the endpoint cannot bind. Failed startup leaves source shutdown with the caller.

Source

pub async fn shutdown(self) -> Result<(), ToolError>

Seals admission and observes the retained server owner through cleanup.

A timeout reports unsettled cleanup; it does not abort the cleanup owner. This example binds a real loopback endpoint and requires an available port. Keep the Tokio runtime driven until both server and toolset cleanup settle. Dropping the server or its shutdown observation signals its retained cleanup owner; only explicit toolset shutdown closes the separate executable source.

§Errors

Returns the retained server cleanup failure, including timeout or handler-cleanup failure. A timeout leaves cleanup owned rather than aborting it.

See McpServer for the complete client/server/source cleanup sequence.

Trait Implementations§

Source§

impl Debug for McpServer

Source§

fn fmt(&self, formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Drop for McpServer

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more