Skip to content

Commit 36d352d

Browse files
committed
Merge remote-tracking branch 'origin/upstream/tool-catalog-1831' into fix/pr62-20-execute-oss-tool-gates
2 parents 5ce1820 + 77723f9 commit 36d352d

4 files changed

Lines changed: 586 additions & 79 deletions

File tree

‎docs/tool-api.md‎

Lines changed: 61 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,11 @@ Response:
3636
}
3737
```
3838

39+
A listed `inputSchema` never has a root-level `oneOf`, `anyOf` or `allOf`,
40+
because several LLM tool APIs reject tool input schemas with root combinators.
41+
Where the catalog schema has one, the server still enforces it when the tool is
42+
called, and the affected property descriptions state the constraint.
43+
3944
The response includes an `ETag` and
4045
`Cache-Control: private, max-age=300, must-revalidate`. A request with a
4146
matching `If-None-Match` receives `304 Not Modified`.
@@ -135,11 +140,15 @@ and pagination are not identical to this summary tool.
135140

136141
`query_sql`, `explain_query` and other tools that run SQL internally parse the
137142
statement with DataFusion's SQL parser and accept exactly one `SELECT` or `WITH`
138-
query. A trailing semicolon and trailing comments are allowed. Every `SELECT`
139-
projection, including those inside nested queries and set operations, must
140-
name at most 10 explicit columns. `*` and `table.*` are rejected. Casts to
141-
`INT64`, `UINT64` or `FLOAT64` are rejected with a hint to use `BIGINT` or
142-
`DOUBLE`. The statement is wrapped with an outer `LIMIT 500`. `sample_events`
143+
query. A trailing semicolon or trailing comments are allowed, but a semicolon
144+
followed by a comment passes validation and then fails when the query runs.
145+
The outermost projection must name at most 10 explicit columns, and `*` and
146+
`table.*` are rejected there. The same limit applies to each branch of a
147+
top-level set operation such as `UNION` and to a parenthesized outer query.
148+
Projections inside CTE definitions, derived tables and subqueries are not
149+
checked. Casts to `INT64`, `UINT64` or `FLOAT64` anywhere in the statement are
150+
rejected with a hint to use `BIGINT` or `DOUBLE`. The statement is wrapped with
151+
an outer `LIMIT 500`. `sample_events`
143152
returns at most 10 columns, choosing common observability fields such as
144153
`p_timestamp`, `service.name`, `severity_text`, `body` and `trace_id` before
145154
other fields.
@@ -150,13 +159,25 @@ other fields.
150159
datasets.
151160

152161
`resolve_dataset` accepts an optional `telemetryType` (`logs`, `metrics` or
153-
`traces`) and `limit` (1–20, default 5). It resolves a `selectedDataset` or
154-
`contextDataset` exactly, or resolves the only visible dataset. Otherwise it
155-
ranks visible datasets by name match against `query`. It resolves only a
156-
unique high-confidence name match. In every other case it returns
157-
`status: "ambiguous"` with up to `limit` scored `candidates`, or `"not_found"`.
158-
It never falls back to an arbitrary dataset. A selected dataset whose telemetry
159-
type does not match `telemetryType` returns `not_found`.
162+
`traces`) and `limit` (1–20, default 5). Its `status` is `resolved`,
163+
`ambiguous`, `not_found` or `error`. Dataset names are matched
164+
case-insensitively.
165+
166+
- A `selectedDataset` or `contextDataset` resolves to the visible dataset with
167+
that name. If no visible dataset has that name, the result has
168+
`status: "error"`. If its telemetry type does not match `telemetryType`, the
169+
result is `not_found`.
170+
- Otherwise, if exactly one dataset is visible, it resolves to that dataset, or
171+
returns `not_found` if its telemetry type does not match.
172+
- Otherwise it scores the visible datasets that match `telemetryType` by name
173+
against `query`: 1000 if the name equals the query, 750 if the query contains
174+
the name, or 500 if the name contains the query, plus 25 for each query term
175+
longer than two characters that the name contains, plus 15 when
176+
`telemetryType` is given. It resolves only a unique top score of at least
177+
500. In every other case it returns `ambiguous` with up to `limit` scored
178+
`candidates`, or `not_found` if no visible dataset matches `telemetryType`.
179+
180+
It never falls back to an arbitrary dataset.
160181

161182
`discover_datasets` counts events in the requested range for each visible
162183
dataset of the requested telemetry type that the caller can query. It returns
@@ -177,12 +198,23 @@ provided together. They take precedence over `minutes`.
177198

178199
`get_log_context` uses the same implementation as `POST /api/v1/query/context`.
179200
Arguments must include exactly one of `log`, `body` or `message`, holding the
180-
anchor row's exact value. The schema enforces this with `oneOf`, so calls with
181-
none or more than one are rejected with `400`. If no context bounds are given,
182-
the window defaults to `contextWindow: "5 minutes"`. Returned records keep at
183-
most 10 fields per row, preferring `p_timestamp`, service, severity, message
184-
and trace identifiers. The response also includes the anchor index, scope and
185-
the executed queries.
201+
anchor row's exact value. The catalog schema enforces this with a root `oneOf`,
202+
so calls with none or more than one are rejected with `400`. The listed
203+
`inputSchema` omits that `oneOf` (see [List tools](#list-tools)) and states the
204+
rule in the property descriptions.
205+
206+
Context bounds are either `contextWindow` or both `contextStartTime` and
207+
`contextEndTime`. Giving only one explicit bound, or a window together with an
208+
explicit bound, is an error. If no bounds are given, the tool uses
209+
`contextWindow: "5 minutes"`. A window extends that duration on each side of
210+
`pTimestamp`, and both ends are rounded down to the minute; if they round to the
211+
same minute, the end is one minute after the start. Explicit bounds are used at
212+
millisecond precision without rounding, and `pTimestamp` must be at or after
213+
the start and before the end. `pageSize` is 1–500, default 100.
214+
215+
Returned records keep at most 10 fields per row, preferring `p_timestamp`,
216+
service, severity, message and trace identifiers. The response also includes
217+
the anchor index, scope and the executed queries.
186218

187219
## Trace activity
188220

@@ -211,14 +243,21 @@ dataset's time partition, or `p_timestamp` if none is configured. The dataset
211243
must have traces telemetry and contain `span_span_id` and `span_trace_id`.
212244
Unknown fields are rejected. `span_count` is `COUNT(DISTINCT span_span_id)` and
213245
`trace_count` is `COUNT(DISTINCT span_trace_id)`, so duplicate span rows are
214-
not double counted. The result contains the exact executed SQL as `query`,
215-
along with `bucketInterval`, `semantics` and up to 500 `rows`. Clients can
216-
rerun that SQL unchanged, for example in a dashboard tile.
246+
not double counted. Rows are ordered by bucket. The result contains `query`,
247+
`bucketInterval`, `semantics` and up to 500 `rows`.
248+
249+
`query` is the aggregation SQL before the tool wraps it with `LIMIT 500`. It
250+
has no time predicate: the time range comes from the request's `startTime` and
251+
`endTime`, which the query API rounds down to the minute. To reproduce the
252+
result, for example in a dashboard tile, run `query` through the query API with
253+
the same `startTime` and `endTime`.
217254

218255
## Argument schema validation
219256

220257
`inputSchema` is enforced server-side for `type` (a single type or a list of types), `required`,
221258
`additionalProperties`, `enum`, `const`, `minLength`/`maxLength`,
222259
`minimum`/`maximum`, `minItems`/`maxItems`, `items`, `anyOf` and `oneOf`.
223260
`oneOf` passes only when exactly one variant matches. Combinators are checked
224-
in addition to sibling keywords; they do not replace them.
261+
in addition to sibling keywords; they do not replace them. Validation uses the
262+
catalog schema, including any root combinators omitted from the listed
263+
`inputSchema`.

‎src/handlers/http/query_context.rs‎

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -376,11 +376,23 @@ fn log_context_window_bounds(
376376

377377
let duration = chrono::Duration::from_std(duration)
378378
.map_err(|err| QueryError::CustomError(format!("Invalid contextWindow: {err}")))?;
379-
let start = truncate_to_minute(anchor_timestamp - duration);
380-
let mut end = truncate_to_minute(anchor_timestamp + duration);
379+
let out_of_range =
380+
|| QueryError::CustomError("contextWindow is outside the supported range".to_string());
381+
let start = truncate_to_minute(
382+
anchor_timestamp
383+
.checked_sub_signed(duration)
384+
.ok_or_else(out_of_range)?,
385+
);
386+
let mut end = truncate_to_minute(
387+
anchor_timestamp
388+
.checked_add_signed(duration)
389+
.ok_or_else(out_of_range)?,
390+
);
381391

382392
if start >= end {
383-
end = start + chrono::Duration::minutes(1);
393+
end = start
394+
.checked_add_signed(chrono::Duration::minutes(1))
395+
.ok_or_else(out_of_range)?;
384396
}
385397

386398
Ok((start, end))
@@ -1202,6 +1214,19 @@ mod tests {
12021214
assert_eq!(format_log_context_api_time(end), "2026-06-17T10:16:00Z");
12031215
}
12041216

1217+
#[test]
1218+
fn log_context_window_bounds_reject_windows_beyond_the_supported_range() {
1219+
for window in ["300000y", "1000000 years"] {
1220+
let error = log_context_window_bounds(anchor_timestamp(), window)
1221+
.unwrap_err()
1222+
.to_string();
1223+
assert!(
1224+
error.contains("contextWindow is outside the supported range"),
1225+
"{window}: {error}"
1226+
);
1227+
}
1228+
}
1229+
12051230
#[test]
12061231
fn log_context_bounds_resolver_accepts_one_mode_only() {
12071232
let anchor = anchor_timestamp();

‎src/tool_catalog.rs‎

Lines changed: 109 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -853,6 +853,25 @@ pub fn external_tool_specs(writes_enabled: bool) -> impl Iterator<Item = &'stati
853853
.chain(WRITES.iter().filter(move |_| writes_enabled))
854854
}
855855

856+
/// Root-level schema combinators that common LLM tool APIs reject in a tool's
857+
/// input schema (Anthropic `input_schema`, OpenAI strict function schemas).
858+
const ROOT_SCHEMA_COMBINATORS: [&str; 3] = ["oneOf", "anyOf", "allOf"];
859+
860+
/// The `inputSchema` advertised to external clients. Root-level combinators
861+
/// are omitted so that one tool cannot break a client's whole tool list; the
862+
/// catalog schema, including those combinators, is still enforced
863+
/// server-side, and affected properties state the constraint in their
864+
/// descriptions.
865+
pub fn listed_input_schema(schema: &Value) -> Value {
866+
let mut schema = schema.clone();
867+
if let Some(object) = schema.as_object_mut() {
868+
for combinator in ROOT_SCHEMA_COMBINATORS {
869+
object.remove(combinator);
870+
}
871+
}
872+
schema
873+
}
874+
856875
/// `GET /api/prism/v1/llm/tools/list`
857876
pub async fn list_tool_registry(request: HttpRequest) -> HttpResponse {
858877
let tools = external_tool_specs(crate::users::dashboard_tools::writes_enabled(&request))
@@ -861,7 +880,7 @@ pub async fn list_tool_registry(request: HttpRequest) -> HttpResponse {
861880
"name": tool.name,
862881
"title": tool.title,
863882
"description": tool.description,
864-
"inputSchema": tool.input_schema,
883+
"inputSchema": listed_input_schema(&tool.input_schema),
865884
"annotations": { "readOnlyHint": matches!(tool.effect(), ToolEffect::ReadOnly | ToolEffect::ExpensiveRead), "destructiveHint": tool.name == "delete_dashboard", "idempotentHint": crate::users::dashboard_tools::is_write(tool.name), "openWorldHint": false },
866885
});
867886
if let Some(schema) = crate::users::dashboard_tools::output_schema(tool.name) { value["outputSchema"] = schema; }
@@ -881,8 +900,9 @@ mod tests {
881900
use serde_json::Value;
882901

883902
use super::{
884-
ToolCallRequest, ToolCallResult, ToolEffect, is_oss_read_tool, list_tool_registry,
885-
oss_action_tool_specs, oss_read_tool_specs, oss_tool_specs,
903+
ROOT_SCHEMA_COMBINATORS, ToolCallRequest, ToolCallResult, ToolEffect, external_tool_specs,
904+
is_oss_read_tool, list_tool_registry, listed_input_schema, oss_action_tool_specs,
905+
oss_read_tool_specs, oss_tool_specs,
886906
};
887907

888908
#[actix_web::test]
@@ -1074,6 +1094,62 @@ mod tests {
10741094
assert_eq!(tool["annotations"]["destructiveHint"], false);
10751095
}
10761096

1097+
#[actix_web::test]
1098+
async fn listed_tools_have_no_root_schema_combinators() {
1099+
let app =
1100+
test::init_service(App::new().route("/tools/list", web::get().to(list_tool_registry)))
1101+
.await;
1102+
let response: Value = test::call_and_read_body_json(
1103+
&app,
1104+
test::TestRequest::get().uri("/tools/list").to_request(),
1105+
)
1106+
.await;
1107+
let listed = response["tools"]
1108+
.as_array()
1109+
.unwrap()
1110+
.iter()
1111+
.map(|tool| {
1112+
(
1113+
tool["name"].as_str().unwrap().to_owned(),
1114+
tool["inputSchema"].clone(),
1115+
)
1116+
})
1117+
.chain(external_tool_specs(true).map(|tool| {
1118+
(
1119+
tool.name.to_owned(),
1120+
listed_input_schema(&tool.input_schema),
1121+
)
1122+
}))
1123+
.collect::<Vec<_>>();
1124+
assert!(listed.iter().any(|(name, _)| name == "get_log_context"));
1125+
for (name, schema) in &listed {
1126+
assert_eq!(schema["type"], "object", "{name}");
1127+
for combinator in ROOT_SCHEMA_COMBINATORS {
1128+
assert!(
1129+
schema.get(combinator).is_none(),
1130+
"{name} lists root {combinator}"
1131+
);
1132+
}
1133+
}
1134+
1135+
// The catalog keeps the constraint for server-side validation, and the
1136+
// listed property descriptions state it.
1137+
let context = external_tool_specs(true)
1138+
.find(|tool| tool.name == "get_log_context")
1139+
.unwrap();
1140+
assert!(context.input_schema.get("oneOf").is_some());
1141+
let listed_context = listed_input_schema(&context.input_schema);
1142+
for anchor in ["log", "body", "message"] {
1143+
assert!(
1144+
listed_context["properties"][anchor]["description"]
1145+
.as_str()
1146+
.unwrap()
1147+
.contains("exactly one of log, body, or message"),
1148+
"{anchor}"
1149+
);
1150+
}
1151+
}
1152+
10771153
#[actix_web::test]
10781154
async fn changed_read_tool_schemas_reject_out_of_contract_arguments() {
10791155
let find = |name: &str| {
@@ -1115,6 +1191,21 @@ mod tests {
11151191
}))
11161192
.is_err()
11171193
);
1194+
for invalid in [
1195+
serde_json::json!({ "dataset": "logs", "pTimestamp": "2026-10-22T00:00:00Z" }),
1196+
serde_json::json!({
1197+
"dataset": "logs",
1198+
"pTimestamp": "2026-10-22T00:00:00Z",
1199+
"log": "a",
1200+
"body": "b"
1201+
}),
1202+
] {
1203+
assert_eq!(
1204+
context.validate_arguments(&invalid).unwrap_err(),
1205+
"arguments must match exactly one allowed schema",
1206+
"{invalid}"
1207+
);
1208+
}
11181209

11191210
let sample = find("sample_events");
11201211
assert!(
@@ -1257,10 +1348,21 @@ mod tests {
12571348
] {
12581349
assert!(validate_tool_arguments(&schema, &value).is_err());
12591350
}
1260-
assert!(
1261-
validate_tool_arguments(&serde_json::json!({"oneOf":[{},{}]}), &serde_json::json!(1))
1262-
.is_err()
1263-
);
1351+
for (schema, value) in [
1352+
// Zero matching variants.
1353+
(
1354+
serde_json::json!({"oneOf":[{"type":"string"},{"type":"boolean"}]}),
1355+
serde_json::json!(1),
1356+
),
1357+
// Two matching variants.
1358+
(serde_json::json!({"oneOf":[{},{}]}), serde_json::json!(1)),
1359+
] {
1360+
assert_eq!(
1361+
validate_tool_arguments(&schema, &value).unwrap_err(),
1362+
"arguments must match exactly one allowed schema",
1363+
"{schema}"
1364+
);
1365+
}
12641366
assert!(
12651367
validate_tool_arguments(
12661368
&serde_json::json!({"anyOf":[{"type":"string"}],"maxLength":2}),

0 commit comments

Comments
 (0)