Skip to main content

micromegas/servers/mcp/
flight.rs

1use super::provider::CallContext;
2use crate::client::flightsql_client::QueryEstimate;
3use crate::client::flightsql_client_factory::{
4    BearerFlightSQLClientFactory, FlightSQLClientFactory,
5};
6use anyhow::Result;
7use arrow::array::RecordBatch;
8use arrow_flight::error::FlightError;
9use async_trait::async_trait;
10use futures::StreamExt;
11use futures::stream::BoxStream;
12use micromegas_telemetry::time_range::TimeRange;
13use std::sync::Arc;
14
15/// Where queries go. Resolved per call so a host can follow a setting that changes at runtime.
16#[async_trait]
17pub trait FlightUrlResolver: Send + Sync {
18    async fn resolve(&self) -> Result<String>;
19}
20
21pub struct FixedUrl(pub String);
22
23#[async_trait]
24impl FlightUrlResolver for FixedUrl {
25    async fn resolve(&self) -> Result<String> {
26        Ok(self.0.clone())
27    }
28}
29
30/// The FlightSQL operations the query tools need. A seam so the tools can be tested without a
31/// server.
32#[async_trait]
33pub trait FlightBackend: Send + Sync {
34    /// Plans the query without running it.
35    async fn prepare(
36        &self,
37        call: &CallContext,
38        sql: &str,
39        range: Option<TimeRange>,
40    ) -> Result<QueryEstimate>;
41
42    /// Starts the query, asking the server for at most `row_limit` rows. Dropping the stream
43    /// cancels it.
44    async fn execute(
45        &self,
46        call: &CallContext,
47        sql: &str,
48        range: Option<TimeRange>,
49        row_limit: usize,
50    ) -> Result<BoxStream<'static, Result<RecordBatch>>>;
51}
52
53/// Talks to a FlightSQL server over gRPC, forwarding the caller's bearer token.
54pub struct GrpcFlightBackend {
55    resolver: Arc<dyn FlightUrlResolver>,
56}
57
58impl GrpcFlightBackend {
59    pub fn new(resolver: Arc<dyn FlightUrlResolver>) -> Self {
60        Self { resolver }
61    }
62
63    // `build_origin_metadata` in the HTTP gateway is not reusable: it suffixes the client type
64    // with `+gateway` and echoes a caller-supplied request id.
65    async fn make_client(
66        &self,
67        call: &CallContext,
68    ) -> Result<crate::client::flightsql_client::Client> {
69        let url = self.resolver.resolve().await?;
70        let mut factory = BearerFlightSQLClientFactory::new_with_client_type(
71            url,
72            call.authorization.clone(),
73            "mcp".to_string(),
74        )
75        .with_metadata("x-client-agent", sanitize_header(&call.client_agent))
76        .with_metadata("x-request-id", uuid::Uuid::new_v4().to_string());
77        if let Some(ip) = forwarded_for_value(&call.client_ip) {
78            factory = factory.with_metadata("x-forwarded-for", ip);
79        }
80        factory.make_client().await
81    }
82}
83
84// FlightSQL resolves the caller address from X-Forwarded-For (see `resolve_client_ip`) and
85// ignores any custom header, so this is what makes allowlists and the audit log see the agent
86// rather than this server. Unparseable values are dropped: the server would ignore them anyway.
87fn forwarded_for_value(client_ip: &str) -> Option<String> {
88    client_ip
89        .trim()
90        .parse::<std::net::IpAddr>()
91        .ok()
92        .map(|ip| ip.to_string())
93}
94
95/// gRPC metadata values must be visible ASCII.
96fn sanitize_header(value: &str) -> String {
97    let cleaned: String = value
98        .chars()
99        .map(|c| {
100            if c.is_ascii_graphic() || c == ' ' {
101                c
102            } else {
103                '?'
104            }
105        })
106        .collect();
107    if cleaned.is_empty() {
108        "unknown".to_string()
109    } else {
110        cleaned
111    }
112}
113
114#[async_trait]
115impl FlightBackend for GrpcFlightBackend {
116    async fn prepare(
117        &self,
118        call: &CallContext,
119        sql: &str,
120        range: Option<TimeRange>,
121    ) -> Result<QueryEstimate> {
122        let mut client = self.make_client(call).await?;
123        client.prepare_query(sql.to_string(), range).await
124    }
125
126    async fn execute(
127        &self,
128        call: &CallContext,
129        sql: &str,
130        range: Option<TimeRange>,
131        row_limit: usize,
132    ) -> Result<BoxStream<'static, Result<RecordBatch>>> {
133        let mut client = self.make_client(call).await?;
134        client
135            .inner_mut()
136            .set_header("limit", row_limit.to_string());
137        let stream = client.query_stream(sql.to_string(), range).await?;
138        Ok(stream.map(|r| r.map_err(anyhow::Error::from)).boxed())
139    }
140}
141
142/// Message shown to the agent for a failed call, naming the gRPC code when there is one.
143pub fn describe_error(error: &anyhow::Error) -> String {
144    let status = error.downcast_ref::<tonic::Status>().or_else(|| {
145        match error.downcast_ref::<FlightError>() {
146            Some(FlightError::Tonic(status)) => Some(status),
147            _ => None,
148        }
149    });
150    match status {
151        Some(status) => format!("{:?}: {}", status.code(), status.message()),
152        None => format!("{error:#}"),
153    }
154}
155
156#[cfg(test)]
157mod forwarded_for_tests {
158    use super::forwarded_for_value;
159
160    #[test]
161    fn forwards_only_parseable_ips() {
162        assert_eq!(forwarded_for_value("10.1.2.3").as_deref(), Some("10.1.2.3"));
163        assert_eq!(forwarded_for_value("::1").as_deref(), Some("::1"));
164        assert_eq!(forwarded_for_value("unknown"), None);
165    }
166}