postgres_mcp/tools/
envelope.rs1use std::time::Duration;
4
5use schemars::JsonSchema;
6use serde::Serialize;
7use serde_json::{Map, Value};
8
9use crate::config::Limits;
10use crate::encode::{EncodeLimits, EncodeStats, dedup_columns, encode_value};
11use crate::gate::SECRET_SETTINGS;
12use crate::pg::session::RunOutput;
13use crate::pg::wire::{Field, Truncation};
14use crate::tools::mask::mask_password_literals;
15
16#[derive(Debug, Serialize, JsonSchema)]
17#[serde(rename_all = "camelCase")]
18pub struct QueryEnvelope {
19 pub database: String,
20 pub columns: Vec<ColumnInfo>,
21 pub rows: Vec<Map<String, Value>>,
22 pub row_count: usize,
23 pub truncated: bool,
24 #[serde(skip_serializing_if = "Option::is_none")]
25 pub truncated_reason: Option<&'static str>,
26 pub truncated_values: u64,
27 pub raw_fallbacks: u64,
28 pub execution_time_ms: u64,
29}
30
31#[derive(Debug, Serialize, JsonSchema)]
32#[serde(rename_all = "camelCase")]
33pub struct ColumnInfo {
34 pub name: String,
35 #[serde(rename = "type")]
36 pub type_name: String,
37 pub type_oid: u32,
38 #[serde(skip_serializing_if = "Option::is_none")]
39 pub original_name: Option<String>,
40}
41
42pub fn build(
44 database: &str,
45 output: RunOutput,
46 limits: &Limits,
47 hide_secret_rows: bool,
48) -> QueryEnvelope {
49 let RunOutput {
50 result,
51 types,
52 elapsed,
53 ..
54 } = output;
55 let raw_names: Vec<String> = result
56 .columns
57 .iter()
58 .map(|c| mask_password_literals(&crate::scrub::scrub(&c.name)).into_owned())
59 .collect();
60 let deduped = dedup_columns(&raw_names);
61 let columns = result
62 .columns
63 .iter()
64 .zip(&types)
65 .zip(&deduped)
66 .map(|((column, ty), (name, original))| ColumnInfo {
67 name: name.clone(),
68 type_name: ty.name.clone(),
69 type_oid: column.type_oid,
70 original_name: original.clone(),
71 })
72 .collect::<Vec<_>>();
73
74 let limits_encode = EncodeLimits {
75 max_value_bytes: limits.max_value_bytes,
76 max_binary_preview_bytes: limits.max_binary_preview_bytes,
77 };
78 let mut stats = EncodeStats::default();
79 let mut rows = Vec::with_capacity(result.rows.len());
80 for row in result.rows {
81 if hide_secret_rows && is_secret_row(&row) {
82 continue;
83 }
84 let mut object = Map::with_capacity(row.len());
85 for (index, cell) in row.into_iter().enumerate() {
86 let value = match cell {
87 Some(field) => encode_value(
88 &field.data,
89 field.full_len,
90 &types[index],
91 &limits_encode,
92 &mut stats,
93 ),
94 None => Value::Null,
95 };
96 object.insert(deduped[index].0.clone(), value);
97 }
98 rows.push(object);
99 }
100
101 let (truncated, truncated_reason) = match result.truncated {
102 None => (false, None),
103 Some(Truncation::Rows) => (true, Some("row_limit")),
104 Some(Truncation::Bytes) => (true, Some("response_size")),
105 };
106 QueryEnvelope {
107 database: database.to_owned(),
108 columns,
109 row_count: rows.len(),
110 rows,
111 truncated,
112 truncated_reason,
113 truncated_values: stats.truncated_values,
114 raw_fallbacks: stats.raw_fallbacks,
115 execution_time_ms: elapsed_ms(elapsed),
116 }
117}
118
119pub fn elapsed_ms(elapsed: Duration) -> u64 {
121 u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX)
122}
123
124fn is_secret_row(row: &[Option<Field>]) -> bool {
126 match row.first() {
127 Some(Some(field)) => std::str::from_utf8(&field.data).is_ok_and(|name| {
128 SECRET_SETTINGS
129 .iter()
130 .any(|secret| secret.eq_ignore_ascii_case(name))
131 }),
132 _ => false,
133 }
134}