Skip to main content

mockql_core/graphql/
mock_response_prompt.rs

1// Copyright 2026 Expedia, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Prompt structures and serialization helpers for mock providers.
16
17use super::mock_directive_extractor::MockedField;
18use schemars::JsonSchema;
19use serde::Deserialize;
20use serde::Serialize;
21use serde_json_bytes::ByteString;
22use serde_json_bytes::Map;
23use serde_json_bytes::Value;
24
25/// Extension key used to store mock-response metadata.
26pub const MOCK_RESPONSE_EXTENSION_KEY: &str = "mockResponse";
27/// Nested debug key stored inside [`MOCK_RESPONSE_EXTENSION_KEY`].
28pub const DEBUG_KEY: &str = "debug";
29/// Key used to store the rendered provider prompt.
30pub const PROMPT_MARKDOWN_KEY: &str = "promptMarkdown";
31/// Key used to store model reasoning for a generated response.
32pub const REASONING_KEY: &str = "reasoning";
33/// Key used to carry a schema extension payload in GraphQL extensions.
34pub const SCHEMA_EXTENSION_KEY: &str = "schemaExtension";
35
36const PROMPT_TEMPLATE: &str = include_str!("prompt-template.md");
37
38/// Output format used when serializing structured prompt sections.
39#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, JsonSchema)]
40#[serde(rename_all = "lowercase")]
41pub enum SerializationFormat {
42  /// Serialize structured sections as JSON.
43  #[default]
44  Json,
45  /// Serialize structured sections in TOON format.
46  Toon,
47}
48
49/// Errors raised while serializing a [`MockResponsePrompt`].
50#[derive(Debug, thiserror::Error)]
51pub enum PromptSerializationError {
52  /// TOON serialization failed.
53  #[error("TOON serialization failed: {0}")]
54  Toon(#[from] toon_format::ToonError),
55  /// JSON serialization failed.
56  #[error("JSON serialization failed: {0}")]
57  Json(#[from] serde_json::Error),
58}
59
60/// Prompt payload sent to a mock provider.
61#[derive(Debug, Clone, Serialize, Deserialize)]
62#[serde(rename_all = "camelCase")]
63pub struct MockResponsePrompt {
64  graphql_schema: String,
65  graphql_operation: String,
66  variables: Map<ByteString, Value>,
67  mocked_fields: Vec<MockedField>,
68  #[serde(default)]
69  partial_response: Option<Value>,
70  #[serde(default, skip_serializing_if = "Option::is_none")]
71  validation_feedback: Option<String>,
72  #[serde(default)]
73  format: SerializationFormat,
74}
75
76const DEBUG_EXCLUDED_KEYS: &[&str] = &["graphqlSchema", "variables"];
77
78fn prompt_template() -> &'static str {
79  PROMPT_TEMPLATE
80    .strip_suffix("\r\n")
81    .or_else(|| PROMPT_TEMPLATE.strip_suffix('\n'))
82    .unwrap_or(PROMPT_TEMPLATE)
83}
84
85fn render_prompt_template(template: &str, replacements: &[(&str, &str)]) -> String {
86  let mut rendered = String::with_capacity(template.len());
87  let mut cursor = 0;
88
89  while cursor < template.len() {
90    let remaining = &template[cursor..];
91    if let Some((token, value)) = replacements.iter().find(|(token, _)| remaining.starts_with(*token)) {
92      rendered.push_str(value);
93      cursor += token.len();
94      continue;
95    }
96
97    let ch = remaining
98      .chars()
99      .next()
100      .expect("remaining template should not be empty");
101    rendered.push(ch);
102    cursor += ch.len_utf8();
103  }
104
105  rendered
106}
107
108#[buildstructor::buildstructor]
109impl MockResponsePrompt {
110  #[builder(visibility = "pub(crate)")]
111  fn new(
112    graphql_schema: String,
113    graphql_operation: String,
114    variables: Map<ByteString, Value>,
115    mocked_fields: Vec<MockedField>,
116    format: SerializationFormat,
117  ) -> Self {
118    Self {
119      graphql_schema,
120      graphql_operation,
121      variables,
122      mocked_fields,
123      partial_response: None,
124      validation_feedback: None,
125      format,
126    }
127  }
128
129  /// Returns a copy of the prompt augmented with upstream partial response data.
130  #[must_use]
131  pub fn with_partial_response(self, partial_response: Option<Value>) -> Self {
132    Self {
133      partial_response,
134      ..self
135    }
136  }
137
138  /// Returns a copy of the prompt augmented with validation feedback.
139  #[must_use]
140  pub fn with_validation_feedback(self, validation_feedback: String) -> Self {
141    Self {
142      validation_feedback: Some(validation_feedback),
143      ..self
144    }
145  }
146
147  fn encode(&self, value: &impl serde::Serialize) -> Result<String, PromptSerializationError> {
148    Ok(match self.format {
149      SerializationFormat::Json => {
150        let encoded = serde_json::to_string(value)?;
151        format!("```json\n{encoded}\n```")
152      }
153      SerializationFormat::Toon => {
154        let options = toon_format::EncodeOptions::new().with_key_folding(toon_format::types::KeyFoldingMode::Safe);
155        let encoded = toon_format::encode(value, &options)?;
156        format!("```toon\n{encoded}\n```")
157      }
158    })
159  }
160
161  /// Attaches prompt debug information to a GraphQL response `extensions` object.
162  pub fn add_to_extensions(&self, extensions: &mut Map<ByteString, Value>) {
163    let Ok(Value::Object(mut debug)) = serde_json_bytes::to_value(self) else {
164      return;
165    };
166    for key in DEBUG_EXCLUDED_KEYS {
167      debug.remove(*key);
168    }
169    if let Ok(markdown) = self.to_markdown() {
170      debug.insert(PROMPT_MARKDOWN_KEY, Value::String(markdown.into()));
171    }
172
173    if let Some(Value::Object(mock_response_extension)) =
174      extensions.get_mut(&ByteString::from(MOCK_RESPONSE_EXTENSION_KEY))
175    {
176      mock_response_extension.insert(DEBUG_KEY, Value::Object(debug));
177    } else {
178      let mut new_mock_response_extension = Map::new();
179      new_mock_response_extension.insert(DEBUG_KEY, Value::Object(debug));
180      extensions.insert(MOCK_RESPONSE_EXTENSION_KEY, Value::Object(new_mock_response_extension));
181    }
182  }
183
184  /// Renders the prompt as provider-facing markdown instructions.
185  pub fn to_markdown(&self) -> Result<String, PromptSerializationError> {
186    let variables_block = self.encode(&self.variables)?;
187    let mocked_fields_block = self.encode(&self.mocked_fields)?;
188
189    let resolved_fields_section = match &self.partial_response {
190      Some(data) => {
191        let block = self.encode(data)?;
192        format!(
193          "### Partial Response\n\
194          GraphQL response returned by the upstream GraphQL server. Use it for contextual mocks.\n\
195          {block}"
196        )
197      }
198      None => String::new(),
199    };
200
201    let validation_feedback_section = self
202      .validation_feedback
203      .as_ref()
204      .map(|feedback| {
205        format!(
206          "### Validation Feedback\n\
207          The previous response failed validation. Generate a complete corrected response that fixes these errors:\n\
208          ```json\n{feedback}\n```"
209        )
210      })
211      .unwrap_or_default();
212    let optional_sections = match (
213      resolved_fields_section.is_empty(),
214      validation_feedback_section.is_empty(),
215    ) {
216      (true, _) => validation_feedback_section,
217      (_, true) => resolved_fields_section,
218      (false, false) => format!("{resolved_fields_section}\n{validation_feedback_section}"),
219    };
220
221    Ok(render_prompt_template(
222      prompt_template(),
223      &[
224        ("__GRAPHQL_SCHEMA__", &self.graphql_schema),
225        ("__GRAPHQL_OPERATION__", &self.graphql_operation),
226        ("__VARIABLES_BLOCK__", &variables_block),
227        ("__MOCKED_FIELDS_BLOCK__", &mocked_fields_block),
228        ("__OPTIONAL_CONTEXT_SECTIONS__", &optional_sections),
229        ("__MOCK_RESPONSE_EXT__", MOCK_RESPONSE_EXTENSION_KEY),
230        ("__REASONING_EXT__", REASONING_KEY),
231      ],
232    ))
233  }
234}
235
236#[cfg(test)]
237mod tests {
238  use super::*;
239  use serde::Deserialize;
240  use std::fs::read_to_string;
241
242  #[derive(Debug, Deserialize)]
243  struct PromptFixture {
244    graphql_schema: String,
245    graphql_operation: String,
246    variables: Map<ByteString, Value>,
247    mocked_fields: Vec<MockedField>,
248    #[serde(default)]
249    format: SerializationFormat,
250    #[serde(default)]
251    partial_response: Option<Value>,
252  }
253
254  #[test]
255  fn to_markdown_matches_snapshot() {
256    insta::glob!("snapshots/mock_response_prompt/*.json", |path| {
257      let fixture: PromptFixture =
258        serde_json::from_str(&read_to_string(path).expect("should read fixture file")).expect("should parse fixture");
259
260      let prompt = MockResponsePrompt::builder()
261        .graphql_schema(fixture.graphql_schema)
262        .graphql_operation(fixture.graphql_operation)
263        .variables(fixture.variables)
264        .mocked_fields(fixture.mocked_fields)
265        .format(fixture.format)
266        .build()
267        .with_partial_response(fixture.partial_response);
268
269      let markdown = prompt.to_markdown().expect("markdown generation should succeed");
270
271      insta::with_settings!({snapshot_path => path.parent().unwrap(), omit_expression => true}, {
272        insta::assert_snapshot!(markdown);
273      });
274    });
275  }
276
277  #[test]
278  fn add_to_extensions_inserts_into_existing_mock_response() {
279    let prompt = MockResponsePrompt::builder()
280      .graphql_schema("T:Query:me:User".to_string())
281      .graphql_operation("{ me { name } }".to_string())
282      .variables(Map::<ByteString, Value>::new())
283      .mocked_fields(vec![])
284      .format(SerializationFormat::Json)
285      .build();
286
287    let mut extensions = Map::new();
288    let mut mock_response = Map::new();
289    mock_response.insert("reasoning", Value::String("test reasoning".into()));
290    extensions.insert(MOCK_RESPONSE_EXTENSION_KEY, Value::Object(mock_response));
291
292    prompt.add_to_extensions(&mut extensions);
293
294    insta::with_settings!({snapshot_path => "snapshots/mock_response_prompt"}, {
295      insta::assert_snapshot!(serde_json::to_string_pretty(&extensions).unwrap());
296    });
297  }
298
299  #[test]
300  fn to_markdown_includes_validation_feedback() {
301    let markdown = MockResponsePrompt::builder()
302      .graphql_schema("T:Query:me:User".to_string())
303      .graphql_operation("{ me { id } }".to_string())
304      .variables(Map::<ByteString, Value>::new())
305      .mocked_fields(vec![])
306      .format(SerializationFormat::Json)
307      .build()
308      .with_validation_feedback(r#"[{"message":"stale error"}]"#.into())
309      .with_validation_feedback(r#"[{"message":"non-null type ID! resolved to null","path":["me","id"]}]"#.into())
310      .to_markdown()
311      .expect("markdown generation should succeed");
312
313    assert!(
314      markdown.contains(
315        "### Validation Feedback\nThe previous response failed validation. Generate a complete corrected response that fixes these errors:\n```json\n[{\"message\":\"non-null type ID! resolved to null\",\"path\":[\"me\",\"id\"]}]\n```"
316      ) && !markdown.contains("stale error")
317    );
318  }
319}