tandem-server 0.6.2

HTTP server for Tandem engine APIs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
use serde_json::{json, Value};
use tandem_runtime::McpPrincipalRef;
use tandem_types::{TenantContext, ToolResult};

use crate::{now_ms, AppState};

const MCP_CONNECTION_ID_ARG: &str = "__mcp_connection_id";
const MCP_CONNECTION_ID_CAMEL_ARG: &str = "__mcpConnectionId";
const MCP_RUN_AS_ARG: &str = "__mcp_run_as";
const MCP_RUN_AS_CAMEL_ARG: &str = "__mcpRunAs";
const MCP_PRINCIPAL_ARG: &str = "__mcp_principal";
const MCP_PRINCIPAL_CAMEL_ARG: &str = "__mcpPrincipal";

#[derive(Debug, Clone)]
struct McpRunAsRequest {
    connection_id: Option<String>,
    principal: Option<McpPrincipalRef>,
}

#[derive(Debug, Clone)]
struct McpRunAsResolution {
    args: Value,
    requested_tenant_context: TenantContext,
    effective_tenant_context: TenantContext,
    connection_id: String,
    principal: McpPrincipalRef,
    connection_class: Option<String>,
    upstream_account: Option<Value>,
    requested_connection_id: Option<String>,
}

pub(crate) async fn call_mcp_tool_for_tenant_with_audit(
    state: &AppState,
    server_name: &str,
    tool_name: &str,
    args: Value,
    tenant_context: &TenantContext,
) -> Result<ToolResult, String> {
    let run_as = resolve_mcp_run_as(state, server_name, tool_name, args, tenant_context).await?;
    let result = state
        .mcp
        .call_tool_for_tenant(
            server_name,
            tool_name,
            run_as.args.clone(),
            &run_as.effective_tenant_context,
        )
        .await;
    if result
        .as_ref()
        .err()
        .is_some_and(|error| mcp_error_is_secret_tenant_mismatch(error))
    {
        append_mcp_secret_tenant_mismatch_audit_event(
            state,
            server_name,
            tool_name,
            &run_as.effective_tenant_context,
        )
        .await;
    }

    append_mcp_tool_execution_audit_event(state, server_name, tool_name, &run_as, &result).await;
    result.map(|mut result| {
        let run_as_payload = run_as.audit_payload();
        if let Some(metadata) = result.metadata.as_object_mut() {
            metadata.insert("mcpRunAs".to_string(), run_as_payload);
        } else {
            result.metadata = json!({ "mcpRunAs": run_as_payload });
        }
        result
    })
}

fn mcp_error_is_secret_tenant_mismatch(error: &str) -> bool {
    error.contains("ToolDenied { reason: TenantScope }")
        && error.contains("store-backed secret header")
        && error.contains("different tenant context")
}

pub(crate) async fn append_mcp_secret_tenant_mismatch_audit_event(
    state: &AppState,
    server_name: &str,
    tool_name: &str,
    tenant_context: &TenantContext,
) {
    let Some(denial) = state
        .mcp
        .secret_tenant_mismatch_audit(server_name, tool_name, tenant_context)
        .await
    else {
        return;
    };
    let _ = crate::audit::append_protected_audit_event(
        state,
        "mcp.secret_tenant_mismatch",
        &denial.tenant_context,
        denial.tenant_context.actor_id.clone(),
        json!({
            "reason": "store_secret_tenant_mismatch",
            "server_name": denial.server_name,
            "tool_name": denial.tool_name,
            "header_names": denial.header_names,
            "tenant_context": denial.tenant_context,
        }),
    )
    .await;
}

async fn resolve_mcp_run_as(
    state: &AppState,
    server_name: &str,
    tool_name: &str,
    args: Value,
    tenant_context: &TenantContext,
) -> Result<McpRunAsResolution, String> {
    let request = extract_mcp_run_as_request(&args);
    let effective_tenant_context = match effective_tenant_context_for_run_as(
        tenant_context,
        request.principal.as_ref(),
    ) {
        Ok(context) => context,
        Err(reason) => {
            append_mcp_run_as_denial_audit_event(
                state,
                server_name,
                tool_name,
                tenant_context,
                tenant_context,
                request.connection_id.as_deref(),
                None,
                &reason,
            )
            .await;
            return Err(format!(
                    "ToolDenied {{ reason: McpRunAsPolicy }}: blocked MCP tool `{server_name}.{tool_name}` because {reason}."
                ));
        }
    };
    let expected_connection_id = state
        .mcp
        .connection_id_for_tenant(server_name, &effective_tenant_context);

    if let Some(requested_connection_id) = request.connection_id.as_deref() {
        if requested_connection_id != expected_connection_id {
            let reason = format!(
                "requested connection `{requested_connection_id}` is not owned by the effective tenant/principal"
            );
            append_mcp_run_as_denial_audit_event(
                state,
                server_name,
                tool_name,
                tenant_context,
                &effective_tenant_context,
                request.connection_id.as_deref(),
                Some(&expected_connection_id),
                &reason,
            )
            .await;
            return Err(format!(
                "ToolDenied {{ reason: McpRunAsPolicy }}: blocked MCP tool `{server_name}.{tool_name}` because {reason}."
            ));
        }
    }

    let connections = state.mcp.list_connections().await;
    let connection = connections.get(&expected_connection_id).cloned();
    let expected_principal = McpPrincipalRef::from_tenant_context(&effective_tenant_context);
    if let Some(connection) = connection.as_ref() {
        if connection.tenant_context != effective_tenant_context
            || connection.owner != expected_principal
        {
            let reason = "stored connection identity did not match the effective tenant/principal";
            append_mcp_run_as_denial_audit_event(
                state,
                server_name,
                tool_name,
                tenant_context,
                &effective_tenant_context,
                request.connection_id.as_deref(),
                Some(&expected_connection_id),
                reason,
            )
            .await;
            return Err(format!(
                "ToolDenied {{ reason: McpRunAsPolicy }}: blocked MCP tool `{server_name}.{tool_name}` because {reason}."
            ));
        }
    }
    if let Some(requested_principal) = request.principal.as_ref() {
        let principal_matches = connection
            .as_ref()
            .map(|connection| requested_principal == &connection.owner)
            .unwrap_or_else(|| requested_principal == &expected_principal);
        if !principal_matches {
            let reason = "requested run-as principal did not match the selected connection";
            append_mcp_run_as_denial_audit_event(
                state,
                server_name,
                tool_name,
                tenant_context,
                &effective_tenant_context,
                request.connection_id.as_deref(),
                Some(&expected_connection_id),
                reason,
            )
            .await;
            return Err(format!(
                "ToolDenied {{ reason: McpRunAsPolicy }}: blocked MCP tool `{server_name}.{tool_name}` because {reason}."
            ));
        }
    }

    Ok(McpRunAsResolution {
        args: strip_mcp_run_as_args(args),
        requested_tenant_context: tenant_context.clone(),
        effective_tenant_context,
        connection_id: expected_connection_id,
        principal: expected_principal,
        connection_class: connection.as_ref().and_then(|connection| {
            serde_json::to_value(&connection.connection_class)
                .ok()
                .and_then(|value| value.as_str().map(str::to_string))
        }),
        upstream_account: connection
            .and_then(|connection| serde_json::to_value(connection.upstream_account).ok())
            .filter(|value| !value.is_null()),
        requested_connection_id: request.connection_id,
    })
}

fn effective_tenant_context_for_run_as(
    tenant_context: &TenantContext,
    principal: Option<&McpPrincipalRef>,
) -> Result<TenantContext, String> {
    let Some(principal) = principal else {
        return Ok(tenant_context.clone());
    };
    match principal {
        McpPrincipalRef::HumanActor { actor_id } => {
            if tenant_context.actor_id.as_deref() == Some(actor_id.as_str()) {
                Ok(tenant_context.clone())
            } else {
                Err(format!(
                    "human actor `{actor_id}` does not match the request tenant actor"
                ))
            }
        }
        McpPrincipalRef::ServicePrincipal { .. } => {
            if tenant_context.actor_id.is_some() {
                return Err(
                    "service-principal MCP run-as requires a server-side connection grant and cannot be selected from an actor-scoped request"
                        .to_string(),
                );
            }
            let mut service_tenant = tenant_context.clone();
            service_tenant.actor_id = None;
            Ok(service_tenant)
        }
        McpPrincipalRef::LocalImplicit => {
            if tenant_context.is_local_implicit() {
                Ok(tenant_context.clone())
            } else {
                Err(
                    "local-implicit MCP connections cannot be selected from explicit tenants"
                        .to_string(),
                )
            }
        }
        McpPrincipalRef::AutomationPrincipal { .. } | McpPrincipalRef::SharedConnection { .. } => {
            Err(
                "the selected delegated MCP principal is not executable by the current bridge"
                    .to_string(),
            )
        }
    }
}

fn extract_mcp_run_as_request(args: &Value) -> McpRunAsRequest {
    let Some(object) = args.as_object() else {
        return McpRunAsRequest {
            connection_id: None,
            principal: None,
        };
    };
    let run_as = object
        .get(MCP_RUN_AS_ARG)
        .or_else(|| object.get(MCP_RUN_AS_CAMEL_ARG));
    let connection_id = object
        .get(MCP_CONNECTION_ID_ARG)
        .or_else(|| object.get(MCP_CONNECTION_ID_CAMEL_ARG))
        .and_then(Value::as_str)
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .map(str::to_string)
        .or_else(|| run_as.and_then(connection_id_from_run_as_value));
    let principal = object
        .get(MCP_PRINCIPAL_ARG)
        .or_else(|| object.get(MCP_PRINCIPAL_CAMEL_ARG))
        .and_then(parse_mcp_principal_ref)
        .or_else(|| run_as.and_then(principal_from_run_as_value));
    McpRunAsRequest {
        connection_id,
        principal,
    }
}

fn connection_id_from_run_as_value(value: &Value) -> Option<String> {
    value
        .get("connection_id")
        .or_else(|| value.get("connectionId"))
        .and_then(Value::as_str)
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .map(str::to_string)
}

fn principal_from_run_as_value(value: &Value) -> Option<McpPrincipalRef> {
    value
        .get("principal")
        .and_then(parse_mcp_principal_ref)
        .or_else(|| parse_mcp_principal_ref(value))
}

fn parse_mcp_principal_ref(value: &Value) -> Option<McpPrincipalRef> {
    serde_json::from_value::<McpPrincipalRef>(value.clone()).ok()
}

fn strip_mcp_run_as_args(args: Value) -> Value {
    let Value::Object(mut object) = args else {
        return args;
    };
    for key in [
        MCP_CONNECTION_ID_ARG,
        MCP_CONNECTION_ID_CAMEL_ARG,
        MCP_RUN_AS_ARG,
        MCP_RUN_AS_CAMEL_ARG,
        MCP_PRINCIPAL_ARG,
        MCP_PRINCIPAL_CAMEL_ARG,
    ] {
        object.remove(key);
    }
    Value::Object(object)
}

async fn append_mcp_run_as_denial_audit_event(
    state: &AppState,
    server_name: &str,
    tool_name: &str,
    requested_tenant_context: &TenantContext,
    effective_tenant_context: &TenantContext,
    requested_connection_id: Option<&str>,
    expected_connection_id: Option<&str>,
    reason: &str,
) {
    let _ = crate::audit::append_protected_audit_event(
        state,
        "mcp.run_as_denied",
        effective_tenant_context,
        requested_tenant_context.actor_id.clone(),
        json!({
            "reason": reason,
            "server_name": server_name,
            "tool_name": tool_name,
            "requested_connection_id": requested_connection_id,
            "expected_connection_id": expected_connection_id,
            "requested_tenant_context": requested_tenant_context,
            "effective_tenant_context": effective_tenant_context,
            "created_at_ms": now_ms(),
        }),
    )
    .await;
}

async fn append_mcp_tool_execution_audit_event(
    state: &AppState,
    server_name: &str,
    tool_name: &str,
    run_as: &McpRunAsResolution,
    result: &Result<ToolResult, String>,
) {
    let _ = crate::audit::append_protected_audit_event(
        state,
        "mcp.tool.execution",
        &run_as.effective_tenant_context,
        run_as.requested_tenant_context.actor_id.clone(),
        json!({
            "status": if result.is_ok() { "completed" } else { "failed" },
            "server_name": server_name,
            "tool_name": tool_name,
            "connection_id": run_as.connection_id,
            "requested_connection_id": run_as.requested_connection_id,
            "principal": run_as.principal,
            "connection_class": run_as.connection_class,
            "upstream_account": run_as.upstream_account,
            "requested_tenant_context": run_as.requested_tenant_context,
            "effective_tenant_context": run_as.effective_tenant_context,
            "error": result.as_ref().err().map(|error| error.as_str()),
        }),
    )
    .await;
}

impl McpRunAsResolution {
    fn audit_payload(&self) -> Value {
        json!({
            "connectionId": self.connection_id,
            "requestedConnectionId": self.requested_connection_id,
            "principal": self.principal,
            "connectionClass": self.connection_class,
            "upstreamAccount": self.upstream_account,
            "requestedTenantContext": self.requested_tenant_context,
            "effectiveTenantContext": self.effective_tenant_context,
        })
    }
}