88//! per server authorizes every request as `Authorization: Bearer <token>`.
99//! `Host` must name the bound address, and a request that sends `Origin`
1010//! (a web page) is refused. Nothing is logged.
11+ //! - The token admits one MCP session. The agent's `initialize` is answered
12+ //! with a random `Mcp-Session-Id`, and every later request must send it. An
13+ //! agent may save its server's token to disk (goose does), so a token read
14+ //! from there is useless once the agent connected.
1115//! - A refused request gets 404, never 401 or 403: MCP clients answer those
1216//! by starting an OAuth sign-in.
13- //! - It is stateless and answers in JSON, never SSE. `POST /mcp` carries one
14- //! message: a request is answered with the page's reply, and a notification
15- //! or response with 202. `GET` and `DELETE` get 405, since there is no
16- //! server stream or session to end .
17+ //! - It answers in JSON, never SSE. `POST /mcp` carries one message: a request
18+ //! is answered with the page's reply, and a notification or response with
19+ //! 202. `GET` and `DELETE` get 405: there is no server stream, and the
20+ //! session ends with the server .
1721//! - Each connection answers one request and closes. A client that closes
1822//! before its answer drops the request; the page's late reply is refused.
1923//! - A server belongs to the plugin and the page that started it. It stops
@@ -29,6 +33,7 @@ use serde::Serialize;
2933use std:: collections:: HashMap ;
3034use std:: convert:: Infallible ;
3135use std:: net:: Ipv4Addr ;
36+ use std:: sync:: atomic:: { AtomicBool , Ordering } ;
3237use std:: sync:: { Arc , Mutex , MutexGuard , PoisonError } ;
3338use std:: time:: Duration ;
3439use tauri:: ipc:: Channel ;
@@ -47,6 +52,7 @@ const BODY_LIMIT: usize = 4 * 1024 * 1024;
4752const BODY_TIMEOUT : Duration = Duration :: from_secs ( 30 ) ;
4853const REPLY_LIMIT : usize = 16 * 1024 * 1024 ;
4954const ENDPOINT : & str = "/mcp" ;
55+ const SESSION : HeaderName = HeaderName :: from_static ( "mcp-session-id" ) ;
5056
5157#[ derive( Clone , Debug , Serialize , PartialEq , Eq ) ]
5258#[ serde( tag = "type" , rename_all = "camelCase" ) ]
@@ -71,6 +77,10 @@ pub(crate) struct McpServerInfo {
7177struct Shared {
7278 authority : String ,
7379 token : String ,
80+ /// The `Mcp-Session-Id` of the one session the token admits.
81+ session : String ,
82+ /// Whether an `initialize` claimed the session.
83+ claimed : AtomicBool ,
7484 events : Channel < McpEvent > ,
7585 stop : CancellationToken ,
7686 pending : Mutex < Pending > ,
@@ -137,12 +147,17 @@ impl HostMcpServers {
137147 let listener = std:: net:: TcpListener :: bind ( ( Ipv4Addr :: LOCALHOST , 0 ) ) . map_err ( failed) ?;
138148 listener. set_nonblocking ( true ) . map_err ( failed) ?;
139149 let authority = listener. local_addr ( ) . map_err ( failed) ?. to_string ( ) ;
140- let mut secret = [ 0 ; 32 ] ;
141- getrandom:: fill ( & mut secret) . map_err ( |_| "Could not start the MCP server" ) ?;
142- let token = URL_SAFE_NO_PAD . encode ( secret) ;
150+ let secret = || {
151+ let mut secret = [ 0 ; 32 ] ;
152+ getrandom:: fill ( & mut secret) . map_err ( |_| "Could not start the MCP server" ) ?;
153+ Ok :: < _ , & str > ( URL_SAFE_NO_PAD . encode ( secret) )
154+ } ;
155+ let token = secret ( ) ?;
143156 let shared = Arc :: new ( Shared {
144157 authority : authority. clone ( ) ,
145158 token : token. clone ( ) ,
159+ session : secret ( ) ?,
160+ claimed : AtomicBool :: new ( false ) ,
146161 events,
147162 stop : CancellationToken :: new ( ) ,
148163 pending : Mutex :: default ( ) ,
@@ -251,22 +266,31 @@ async fn answer(
251266 shared : & Shared ,
252267 request : Request < Incoming > ,
253268) -> Result < Response < Full < Bytes > > , Infallible > {
254- let ( status, body) = match refuse ( shared, & request) {
255- Some ( status) => ( status, None ) ,
256- None => {
269+ let ( status, body, joined ) = match refuse ( shared, & request) {
270+ Err ( status) => ( status, None , false ) ,
271+ Ok ( named ) => {
257272 let body = Limited :: new ( request. into_body ( ) , BODY_LIMIT ) . collect ( ) ;
258273 match tokio:: time:: timeout ( BODY_TIMEOUT , body) . await {
259274 Ok ( Ok ( body) ) => match String :: from_utf8 ( body. to_bytes ( ) . into ( ) ) {
260- Ok ( body) => forward ( shared, body) . await ,
261- Err ( _) => ( StatusCode :: BAD_REQUEST , None ) ,
275+ Ok ( body) => match join ( shared, named, & body) {
276+ Ok ( joined) => {
277+ let ( status, reply) = forward ( shared, body) . await ;
278+ ( status, reply, joined)
279+ }
280+ Err ( status) => ( status, None , false ) ,
281+ } ,
282+ Err ( _) => ( StatusCode :: BAD_REQUEST , None , false ) ,
262283 } ,
263- _ => ( StatusCode :: BAD_REQUEST , None ) ,
284+ _ => ( StatusCode :: BAD_REQUEST , None , false ) ,
264285 }
265286 }
266287 } ;
267288 let mut response = Response :: builder ( )
268289 . status ( status)
269290 . header ( header:: CACHE_CONTROL , "no-store" ) ;
291+ if joined && ( status == StatusCode :: OK || status == StatusCode :: ACCEPTED ) {
292+ response = response. header ( SESSION , & shared. session ) ;
293+ }
270294 if status == StatusCode :: OK {
271295 response = response. header ( header:: CONTENT_TYPE , "application/json" ) ;
272296 }
@@ -311,8 +335,9 @@ async fn forward(shared: &Shared, body: String) -> (StatusCode, Option<String>)
311335 }
312336}
313337
314- /// The status that refuses `request`, unless it is an authorized `POST /mcp`.
315- fn refuse ( shared : & Shared , request : & Request < Incoming > ) -> Option < StatusCode > {
338+ /// Whether an authorized `POST /mcp` names the session, or the status that
339+ /// refuses `request`.
340+ fn refuse ( shared : & Shared , request : & Request < Incoming > ) -> Result < bool , StatusCode > {
316341 let token = header ( request, header:: AUTHORIZATION )
317342 . and_then ( |value| value. strip_prefix ( "Bearer " ) )
318343 . unwrap_or_default ( ) ;
@@ -322,23 +347,52 @@ fn refuse(shared: &Shared, request: &Request<Incoming>) -> Option<StatusCode> {
322347 || request. uri ( ) . path ( ) != ENDPOINT
323348 || !same ( token. as_bytes ( ) , shared. token . as_bytes ( ) )
324349 {
325- return Some ( StatusCode :: NOT_FOUND ) ;
350+ return Err ( StatusCode :: NOT_FOUND ) ;
326351 }
327352 // No server stream for `GET` and no session for `DELETE` to end.
328353 if request. method ( ) != Method :: POST {
329- return Some ( StatusCode :: METHOD_NOT_ALLOWED ) ;
354+ return Err ( StatusCode :: METHOD_NOT_ALLOWED ) ;
330355 }
331356 let json = header ( request, header:: CONTENT_TYPE )
332357 . and_then ( |value| value. split ( ';' ) . next ( ) )
333358 . is_some_and ( |kind| kind. trim ( ) . eq_ignore_ascii_case ( "application/json" ) ) ;
334359 if !json {
335- return Some ( StatusCode :: UNSUPPORTED_MEDIA_TYPE ) ;
360+ return Err ( StatusCode :: UNSUPPORTED_MEDIA_TYPE ) ;
336361 }
337362 let length = header ( request, header:: CONTENT_LENGTH ) . and_then ( |value| value. parse ( ) . ok ( ) ) ;
338363 if length. is_some_and ( |length : usize | length > BODY_LIMIT ) {
339- return Some ( StatusCode :: PAYLOAD_TOO_LARGE ) ;
364+ return Err ( StatusCode :: PAYLOAD_TOO_LARGE ) ;
365+ }
366+ match header ( request, SESSION ) {
367+ Some ( session) if same ( session. as_bytes ( ) , shared. session . as_bytes ( ) ) => Ok ( true ) ,
368+ Some ( _) => Err ( StatusCode :: NOT_FOUND ) ,
369+ None => Ok ( false ) ,
370+ }
371+ }
372+
373+ /// Whether `body` is in the session: it named it, or it is the `initialize`
374+ /// that claims it. Until then a message may come without one, as a client's
375+ /// `server/discover` does; after it, the token alone admits nothing.
376+ fn join ( shared : & Shared , named : bool , body : & str ) -> Result < bool , StatusCode > {
377+ #[ derive( serde:: Deserialize ) ]
378+ struct Message {
379+ method : Option < String > ,
380+ }
381+ if named {
382+ return Ok ( true ) ;
383+ }
384+ let initialize = serde_json:: from_str :: < Message > ( body)
385+ . is_ok_and ( |message| message. method . as_deref ( ) == Some ( "initialize" ) ) ;
386+ let claimed = if initialize {
387+ shared. claimed . swap ( true , Ordering :: SeqCst )
388+ } else {
389+ shared. claimed . load ( Ordering :: SeqCst )
390+ } ;
391+ if claimed {
392+ Err ( StatusCode :: NOT_FOUND )
393+ } else {
394+ Ok ( initialize)
340395 }
341- None
342396}
343397
344398fn header ( request : & Request < Incoming > , name : HeaderName ) -> Option < & str > {
0 commit comments