Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(prompts): resolve prompt references at fetch time (#102076)

Juraj Majerik84180b25ceee
diff --git a/posthog/api/llm_prompt.py b/posthog/api/llm_prompt.py
index aedee9f3960c..74c1d1ca843b 100644
--- a/posthog/api/llm_prompt.py
+++ b/posthog/api/llm_prompt.py
@@ -8,6 +8,7 @@ from django.db import IntegrityError
from django.db.models import Func, IntegerField, Q, QuerySet, TextField
from django.db.models.functions import Cast
+import posthoganalytics
from drf_spectacular.utils import OpenApiResponse, extend_schema
from rest_framework import mixins, serializers, status, viewsets
from rest_framework.decorators import action
@@ -66,7 +67,7 @@ from posthog.auth import (
)
from posthog.event_usage import report_team_action, report_user_action
from posthog.exceptions_capture import capture_exception
-from posthog.models import User
+from posthog.models import Team, User
from posthog.permissions import AccessControlPermission
from posthog.rate_limit import BurstRateThrottle, LLMPromptPublishBurstRateThrottle, SustainedRateThrottle
from posthog.storage.llm_prompt_cache import get_prompt_by_name_from_cache
@@ -75,11 +76,33 @@ from products.access_control.backend.presentation.access_control import AccessCo
from products.ai_observability.backend.activity_logging import log_llm_prompt_activity
from products.ai_observability.backend.api.metrics import llma_track_latency
from products.ai_observability.backend.models.llm_prompt import LLMPrompt, LLMPromptLabel, get_prompt_outline
+from products.ai_observability.backend.prompt_references import PromptReferenceResolutionError, assemble_prompt_payload
PROMPT_FETCHED_EVENT = "$llm_prompt_fetched"
PROMPT_FETCHED_EVENT_SOURCE = "llm_prompt_management"
+PROMPT_PARTIALS_FLAG = "prompt-partials"
+
+
+def prompt_partials_enabled(team: Team) -> bool:
+ """Kill switch for fetch-time reference resolution. Flag off = tags pass through as plain text."""
+ try:
+ return bool(
+ posthoganalytics.feature_enabled(
+ PROMPT_PARTIALS_FLAG,
+ str(team.uuid),
+ groups={"organization": str(team.organization_id), "project": str(team.id)},
+ group_properties={"organization": {"id": str(team.organization_id)}},
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ )
+ except Exception:
+ # Flag service unavailable must not take down the SDK fetch path.
+ return False
+
+
@extend_schema(extensions={"x-product": "llm_analytics"})
class LLMPromptViewSet(
TeamAndOrgViewSetMixin,
@@ -206,6 +229,12 @@ class LLMPromptViewSet(
"prompt_first_version_created_at": prompt["first_version_created_at"],
"prompt_has_config": prompt.get("config") is not None,
"prompt_fetch_path": fetch_path,
+ # Which partial versions were live in this exact response, so traces
+ # answer "what guardrails text did this call actually get".
+ "prompt_reference_count": len(prompt.get("resolved_references") or []),
+ "prompt_resolved_references": [
+ f"{r['name']}@v{r['version']}" for r in (prompt.get("resolved_references") or [])
+ ],
}
def _track_prompt_fetch(self, prompt: dict[str, Any]) -> None:
@@ -330,6 +359,7 @@ class LLMPromptViewSet(
version = cast(int | None, query_params.get("version"))
label = cast(str | None, query_params.get("label"))
content_mode = cast(str, query_params.get("content", "full"))
+ resolve = cast(bool, query_params.get("resolve", True))
resolved_name = self._resolve_prompt_name(prompt_name)
if resolved_name is None:
return self._prompt_not_found_response(prompt_name)
@@ -357,6 +387,17 @@ class LLMPromptViewSet(
)
return self._prompt_not_found_response(prompt_name)
+ if resolve and content_mode == "full" and prompt_partials_enabled(self.team):
+ try:
+ prompt = assemble_prompt_payload(self.team, prompt)
+ except PromptReferenceResolutionError as err:
+ error_status: int = status.HTTP_409_CONFLICT
+ if err.unavailable:
+ error_status = status.HTTP_503_SERVICE_UNAVAILABLE
+ elif err.missing:
+ error_status = status.HTTP_404_NOT_FOUND
+ return Response({"detail": err.message, "reference_name": err.reference_name}, status=error_status)
+
self._track_prompt_fetch(prompt)
return Response(self._apply_content_mode(prompt, content_mode))
diff --git a/posthog/api/llm_prompt_serializers.py b/posthog/api/llm_prompt_serializers.py
index 6feb076cf438..2f83f69c026e 100644
--- a/posthog/api/llm_prompt_serializers.py
+++ b/posthog/api/llm_prompt_serializers.py
@@ -153,6 +153,15 @@ class LLMPromptGetByNameQuerySerializer(LLMPromptFetchQuerySerializer):
default="full",
help_text=CONTENT_MODE_HELP,
)
+ resolve = serializers.BooleanField(
+ required=False,
+ default=True,
+ help_text=(
+ "Replace @@@prompt:...@@@ references with the referenced prompts' content before returning. "
+ "Set to false to get the raw text with the reference tags, e.g. for editing or export. "
+ "Only applies when content is 'full'."
+ ),
+ )
def validate_label(self, value: str) -> str:
# Fetching also writes to the cache (miss sentinels under caller-controlled keys),
@@ -550,6 +559,15 @@ class LLMPromptVersionSummarySerializer(serializers.ModelSerializer):
return sorted(label.name for label in instance.labels.all())
+class LLMPromptResolvedReferenceSerializer(serializers.Serializer):
+ name = serializers.CharField(help_text="Name of the referenced prompt that was spliced in.")
+ version = serializers.IntegerField(help_text="Exact version whose content was spliced in.")
+ label = serializers.CharField( # type: ignore[assignment]
+ allow_null=True,
+ help_text="Label the reference used, or null when it pinned a version directly.",
+ )
+
+
class LLMPromptPublicSerializer(serializers.Serializer):
id = serializers.UUIDField()
name = serializers.CharField()
@@ -578,6 +596,14 @@ class LLMPromptPublicSerializer(serializers.Serializer):
required=False,
help_text="The label this prompt was fetched by. Only present when fetching with the label parameter.",
)
+ resolved_references = LLMPromptResolvedReferenceSerializer(
+ many=True,
+ required=False,
+ help_text=(
+ "The exact prompt versions spliced into the returned content, in order of first appearance. "
+ "Empty when the prompt has no references. Only present when references were resolved."
+ ),
+ )
created_at = serializers.DateTimeField()
updated_at = serializers.DateTimeField()
deleted = serializers.BooleanField()
diff --git a/posthog/api/test/test_llm_prompt.py b/posthog/api/test/test_llm_prompt.py
index 2191f6843ad6..0333ce7d9631 100644
--- a/posthog/api/test/test_llm_prompt.py
+++ b/posthog/api/test/test_llm_prompt.py
@@ -23,6 +23,7 @@ from posthog.api.llm_prompt_serializers import (
from posthog.api.services.llm_prompt import MAX_PROMPT_VERSION
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.rate_limit import BurstRateThrottle, LLMPromptPublishBurstRateThrottle, SustainedRateThrottle
+from posthog.storage.llm_prompt_cache import get_prompt_by_name_from_cache
from products.ai_observability.backend.models.llm_prompt import LLMPrompt, LLMPromptDependency, LLMPromptLabel
from products.ai_observability.backend.prompt_references import MAX_PROMPT_REFERENCES
@@ -2014,3 +2015,180 @@ class TestLLMPromptDependenciesAPI(APIBaseTest):
self.client.delete(f"/api/environments/{self.team.id}/llm_prompts/name/base/labels/prod/").status_code
== status.HTTP_204_NO_CONTENT
)
+
+ @patch("posthog.api.llm_prompt.prompt_partials_enabled", return_value=True)
+ def test_fetch_resolves_references_into_assembled_content(self, _flag):
+ self._make_prompt("guardrails", prompt="Never lie.", label="production")
+ self._make_prompt("tone", prompt="Be kind.", version=3)
+ self.client.post(
+ f"/api/environments/{self.team.id}/llm_prompts/",
+ data={
+ "name": "agent",
+ "prompt": "Intro\n@@@prompt:name=guardrails|label=production@@@\n@@@prompt:name=tone|version=3@@@",
+ },
+ format="json",
+ )
+
+ response = self.client.get(f"/api/environments/{self.team.id}/llm_prompts/name/agent/")
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["prompt"] == "Intro\nNever lie.\nBe kind."
+ assert response.json()["resolved_references"] == [
+ {"name": "guardrails", "version": 1, "label": "production"},
+ {"name": "tone", "version": 3, "label": None},
+ ]
+
+ @patch("posthog.api.llm_prompt.prompt_partials_enabled", return_value=False)
+ def test_fetch_passes_tags_through_when_flag_is_off(self, _flag):
+ self._make_prompt("guardrails", label="production")
+ self.client.post(
+ f"/api/environments/{self.team.id}/llm_prompts/",
+ data={"name": "agent", "prompt": "@@@prompt:name=guardrails|label=production@@@"},
+ format="json",
+ )
+
+ response = self.client.get(f"/api/environments/{self.team.id}/llm_prompts/name/agent/")
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["prompt"] == "@@@prompt:name=guardrails|label=production@@@"
+ assert "resolved_references" not in response.json()
+
+ @patch("posthog.api.llm_prompt.prompt_partials_enabled", return_value=True)
+ def test_fetch_with_resolve_false_returns_raw_tags(self, _flag):
+ self._make_prompt("guardrails", label="production")
+ self.client.post(
+ f"/api/environments/{self.team.id}/llm_prompts/",
+ data={"name": "agent", "prompt": "@@@prompt:name=guardrails|label=production@@@"},
+ format="json",
+ )
+
+ response = self.client.get(f"/api/environments/{self.team.id}/llm_prompts/name/agent/?resolve=false")
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["prompt"] == "@@@prompt:name=guardrails|label=production@@@"
+
+ @patch("posthog.api.llm_prompt.prompt_partials_enabled", return_value=True)
+ def test_label_move_changes_the_assembled_fetch(self, _flag):
+ self._make_prompt("guardrails", prompt="Old rules.", label="prod")
+ self.client.post(
+ f"/api/environments/{self.team.id}/llm_prompts/",
+ data={"name": "agent", "prompt": "@@@prompt:name=guardrails|label=prod@@@"},
+ format="json",
+ )
+ first = self.client.get(f"/api/environments/{self.team.id}/llm_prompts/name/agent/")
+ assert first.json()["prompt"] == "Old rules."
+
+ with self.captureOnCommitCallbacks(execute=True):
+ self.client.patch(
+ f"/api/environments/{self.team.id}/llm_prompts/name/guardrails/",
+ data={"prompt": "New rules.", "base_version": 1},
+ format="json",
+ )
+ self.client.put(
+ f"/api/environments/{self.team.id}/llm_prompts/name/guardrails/labels/prod/",
+ data={"version": 2},
+ format="json",
+ )
+
+ second = self.client.get(f"/api/environments/{self.team.id}/llm_prompts/name/agent/")
+ assert second.json()["prompt"] == "New rules."
+ assert second.json()["resolved_references"] == [{"name": "guardrails", "version": 2, "label": "prod"}]
+
+ @patch("posthog.api.llm_prompt.prompt_partials_enabled", return_value=True)
+ def test_fetch_404s_naming_a_missing_referenced_prompt(self, _flag):
+ self._make_prompt("guardrails")
+ self.client.post(
+ f"/api/environments/{self.team.id}/llm_prompts/",
+ data={"name": "agent", "prompt": "@@@prompt:name=guardrails|version=1@@@"},
+ format="json",
+ )
+ LLMPrompt.objects.filter(team=self.team, name="guardrails").update(deleted=True)
+
+ response = self.client.get(f"/api/environments/{self.team.id}/llm_prompts/name/agent/")
+
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+ assert response.json()["reference_name"] == "guardrails"
+ assert "guardrails" in response.json()["detail"]
+
+ @patch("posthog.api.llm_prompt.prompt_partials_enabled", return_value=True)
+ def test_fetch_409s_on_nested_references(self, _flag):
+ self._make_prompt("base")
+ self._make_prompt("mid", prompt="@@@prompt:name=base|version=1@@@")
+ # Bypasses publish validation the way a raced write would.
+ self._make_prompt("top", prompt="@@@prompt:name=mid|version=1@@@")
+
+ response = self.client.get(f"/api/environments/{self.team.id}/llm_prompts/name/top/")
+
+ assert response.status_code == status.HTTP_409_CONFLICT
+ assert response.json()["reference_name"] == "mid"
+
+ @patch("posthog.api.llm_prompt.prompt_partials_enabled", return_value=True)
+ def test_fetch_409s_when_assembly_exceeds_the_size_cap(self, _flag):
+ self._make_prompt("big", prompt="x" * 600_000)
+ # Two tags to the same 600k partial: each version is under the cap,
+ # the assembly is not. Bypasses publish validation like a raced label move.
+ self._make_prompt("agent", prompt="@@@prompt:name=big|version=1@@@@@@prompt:name=big|version=1@@@")
+
+ response = self.client.get(f"/api/environments/{self.team.id}/llm_prompts/name/agent/")
+
+ assert response.status_code == status.HTTP_409_CONFLICT
+ assert response.json()["reference_name"] == "agent"
+
+ @patch("posthog.api.llm_prompt.prompt_partials_enabled", return_value=True)
+ def test_repeated_tags_cost_one_lookup_and_one_provenance_entry(self, _flag):
+ self._make_prompt("guardrails", prompt="G.", label="production")
+ tag = "@@@prompt:name=guardrails|label=production@@@"
+ self.client.post(
+ f"/api/environments/{self.team.id}/llm_prompts/",
+ data={"name": "agent", "prompt": f"{tag}\n{tag}\n{tag}"},
+ format="json",
+ )
+
+ with patch(
+ "products.ai_observability.backend.prompt_references.get_prompt_by_name_from_cache",
+ side_effect=get_prompt_by_name_from_cache,
+ ) as cache_read:
+ response = self.client.get(f"/api/environments/{self.team.id}/llm_prompts/name/agent/")
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["prompt"] == "G.\nG.\nG."
+ assert response.json()["resolved_references"] == [{"name": "guardrails", "version": 1, "label": "production"}]
+ assert cache_read.call_count == 1
+
+ @patch("posthog.api.llm_prompt.prompt_partials_enabled", return_value=True)
+ def test_assembly_exactly_at_the_cap_is_accepted(self, _flag):
+ # Padding plus spliced content fits the cap only if the tag's own
+ # bytes are not double counted; the overcounting bug rejected this.
+ self._make_prompt("big", prompt="x" * 600_000)
+ tag = "@@@prompt:name=big|version=1@@@"
+ padding = "y" * (1_000_000 - 600_000)
+
+ create = self.client.post(
+ f"/api/environments/{self.team.id}/llm_prompts/",
+ data={"name": "agent", "prompt": padding + tag},
+ format="json",
+ )
+ assert create.status_code == status.HTTP_201_CREATED
+
+ response = self.client.get(f"/api/environments/{self.team.id}/llm_prompts/name/agent/")
+ assert response.status_code == status.HTTP_200_OK
+ assert len(response.json()["prompt"]) == 1_000_000
+
+ @patch("posthog.api.llm_prompt.prompt_partials_enabled", return_value=True)
+ def test_transient_reference_lookup_failure_is_503_not_404(self, _flag):
+ # A database outage degrades the cached lookup to None; that must not
+ # tell SDK callers the referenced prompt "no longer exists".
+ self._make_prompt("guardrails", label="production")
+ self.client.post(
+ f"/api/environments/{self.team.id}/llm_prompts/",
+ data={"name": "agent", "prompt": "@@@prompt:name=guardrails|label=production@@@"},
+ format="json",
+ )
+
+ with patch(
+ "products.ai_observability.backend.prompt_references.get_prompt_by_name_from_cache", return_value=None
+ ):
+ response = self.client.get(f"/api/environments/{self.team.id}/llm_prompts/name/agent/")
+
+ assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE
+ assert response.json()["reference_name"] == "guardrails"
diff --git a/products/ai_observability/backend/prompt_references.py b/products/ai_observability/backend/prompt_references.py
index 7dcc855bb7da..cd721126a2fa 100644
--- a/products/ai_observability/backend/prompt_references.py
+++ b/products/ai_observability/backend/prompt_references.py
@@ -2,12 +2,15 @@ import re
from collections import Counter
from typing import Any
+from django.db import InterfaceError, OperationalError
from django.db.models import Q
from rest_framework import serializers
from posthog.dataclasses import frozen
from posthog.llm_prompt import MAX_PROMPT_PAYLOAD_BYTES, normalize_prompt_to_string
+from posthog.models.team.team import Team
+from posthog.storage.llm_prompt_cache import get_prompt_by_name_from_cache
from products.ai_observability.backend.models.llm_prompt import LLMPrompt, LLMPromptDependency, LLMPromptLabel
@@ -136,7 +139,10 @@ def validate_prompt_references(team_id: int, *, prompt_name: str, prompt_payload
"referenced_prompt_cannot_reference",
)
- assembled_bytes = len(text.encode("utf-8"))
+ # True assembled size: the tags are replaced by content at resolution,
+ # so their bytes leave the total.
+ tag_bytes = sum(len(match.group(0).encode("utf-8")) for match in PROMPT_REFERENCE_REGEX.finditer(text))
+ assembled_bytes = len(text.encode("utf-8")) - tag_bytes
for reference in references:
if reference.name == prompt_name:
raise _reference_error(
@@ -244,3 +250,122 @@ def record_prompt_references(prompt: LLMPrompt) -> list[LLMPromptDependency]:
for reference in unique_references
]
)
+
+
+@frozen
+class PromptReferenceResolutionError(Exception):
+ """A fetched prompt's reference cannot be spliced in.
+
+ `missing` distinguishes "the referenced prompt/version/label is gone"
+ (a 404 for the caller) from "the referenced content is in a state
+ validation normally prevents", e.g. nested references or an oversized
+ assembly reached through a raced label move (a 409). `unavailable` means
+ the reference could not be checked at all (a 503): the caller should
+ retry, not edit their prompt.
+ """
+
+ reference_name: str
+ message: str
+ missing: bool
+ unavailable: bool = False
+
+
+def _confirm_reference_missing(team_id: int, name: str, version: str | None, label: str | None) -> bool:
+ """Distinguish a genuinely absent reference target from a database outage.
+
+ The cached read path deliberately degrades transient database errors to
+ None. Served raw, that tells SDK callers the referenced prompt "no longer
+ exists" during an outage. This direct check runs only on the miss path,
+ so the warm fetch stays cache-only.
+ """
+ try:
+ if version is not None:
+ return not LLMPrompt.objects.filter(
+ team_id=team_id, name=name, version=int(version), deleted=False
+ ).exists()
+ return not LLMPromptLabel.objects.filter(
+ team_id=team_id, prompt_name=name, name=label, prompt__deleted=False
+ ).exists()
+ except (OperationalError, InterfaceError):
+ return False
+
+
+def assemble_prompt_payload(team: Team, payload: dict[str, Any]) -> dict[str, Any]:
+ """Splice referenced prompts' content into a fetched payload.
+
+ Each referenced prompt resolves through the same cached read path as the
+ payload itself, so staleness stays inside the documented cache TTLs and a
+ warm fetch costs one cache read per referenced prompt. Depth is one level
+ by validation, so there is no recursion. Raises
+ PromptReferenceResolutionError instead of ever returning a payload with a
+ raw tag or a hole where referenced content should be.
+ """
+ content = payload.get("prompt")
+ if not isinstance(content, str) or not PROMPT_REFERENCE_REGEX.search(content):
+ return {**payload, "resolved_references": []}
+
+ resolved: list[dict[str, Any]] = []
+ # Publish validation caps unique references, not occurrences: a 1 MB body
+ # can hold ~35k copies of one small tag whose label later moves to a large
+ # version. Memoizing bounds the cache reads to the unique references, and
+ # the running size check aborts before a large assembly is materialized,
+ # so a fetch never allocates more than the payload cap.
+ memoized: dict[tuple[str, str | None, str | None], str] = {}
+ # Running total of the true assembled size: each replacement removes the
+ # tag's bytes and adds the spliced content's bytes.
+ assembled_bytes = len(content.encode("utf-8"))
+
+ def _splice(match: re.Match[str]) -> str:
+ nonlocal assembled_bytes
+ name = match.group("name")
+ version = match.group("version")
+ label = match.group("label")
+ key = (name, version, label)
+ child_content = memoized.get(key)
+ if child_content is None:
+ child = get_prompt_by_name_from_cache(
+ team, name, int(version) if version is not None else None, label=label
+ )
+ if child is None:
+ if not _confirm_reference_missing(team.id, name, version, label):
+ raise PromptReferenceResolutionError(
+ reference_name=name,
+ message=f"Couldn't load the referenced prompt '{name}' right now. Try again.",
+ missing=False,
+ unavailable=True,
+ )
+ selector = f"version {version}" if version is not None else f"label '{label}'"
+ raise PromptReferenceResolutionError(
+ reference_name=name,
+ message=f"This prompt references '{name}' at {selector}, which no longer exists.",
+ missing=True,
+ )
+ child_content = child.get("prompt")
+ if not isinstance(child_content, str):
+ raise PromptReferenceResolutionError(
+ reference_name=name,
+ message=f"The referenced prompt '{name}' is not plain text and cannot be spliced in.",
+ missing=False,
+ )
+ if PROMPT_REFERENCE_REGEX.search(child_content):
+ raise PromptReferenceResolutionError(
+ reference_name=name,
+ message=f"The referenced prompt '{name}' contains references of its own and cannot be spliced in.",
+ missing=False,
+ )
+ memoized[key] = child_content
+ resolved.append({"name": name, "version": child["version"], "label": label})
+ assembled_bytes += len(child_content.encode("utf-8")) - len(match.group(0).encode("utf-8"))
+ if assembled_bytes > MAX_PROMPT_PAYLOAD_BYTES:
+ raise PromptReferenceResolutionError(
+ reference_name=payload["name"],
+ message=(
+ f"The prompt with all referenced content included exceeds {MAX_PROMPT_PAYLOAD_BYTES} bytes. "
+ "Shorten the prompt or its referenced prompts."
+ ),
+ missing=False,
+ )
+ return child_content
+
+ assembled = PROMPT_REFERENCE_REGEX.sub(_splice, content)
+ return {**payload, "prompt": assembled, "resolved_references": resolved}
diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.ts
index d0f2fcbfe971..93b041e06d97 100644
--- a/products/ai_observability/frontend/generated/api.schemas.ts
+++ b/products/ai_observability/frontend/generated/api.schemas.ts
@@ -2718,6 +2718,18 @@ export interface LLMPromptApi {
*/
export type LLMPromptPublicApiConfig = { [key: string]: unknown } | null
+export interface LLMPromptResolvedReferenceApi {
+ /** Name of the referenced prompt that was spliced in. */
+ name: string
+ /** Exact version whose content was spliced in. */
+ version: number
+ /**
+ * Label the reference used, or null when it pinned a version directly.
+ * @nullable
+ */
+ label: string | null
+}
+
export interface LLMPromptPublicApi {
id: string
name: string
@@ -2735,6 +2747,8 @@ export interface LLMPromptPublicApi {
version: number
/** The label this prompt was fetched by. Only present when fetching with the label parameter. */
label?: string
+ /** The exact prompt versions spliced into the returned content, in order of first appearance. Empty when the prompt has no references. Only present when references were resolved. */
+ resolved_references?: LLMPromptResolvedReferenceApi[]
created_at: string
updated_at: string
deleted: boolean
@@ -3636,6 +3650,10 @@ export type LlmPromptsNameRetrieveParams = {
* @maxLength 128
*/
label?: string
+ /**
+ * Replace @@@prompt:...@@@ references with the referenced prompts' content before returning. Set to false to get the raw text with the reference tags, e.g. for editing or export. Only applies when content is 'full'.
+ */
+ resolve?: boolean
/**
* Specific prompt version to fetch. If omitted, the latest version is returned.
* @minimum 1
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 40e696944128..37350fbae658 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -50676,6 +50676,18 @@ export namespace Schemas {
*/
export type LLMPromptPublicConfig = { [key: string]: unknown } | null;
+ export interface LLMPromptResolvedReference {
+ /** Name of the referenced prompt that was spliced in. */
+ name: string;
+ /** Exact version whose content was spliced in. */
+ version: number;
+ /**
+ * Label the reference used, or null when it pinned a version directly.
+ * @nullable
+ */
+ label: string | null;
+ }
+
export interface LLMPromptPublic {
id: string;
name: string;
@@ -50693,6 +50705,8 @@ export namespace Schemas {
version: number;
/** The label this prompt was fetched by. Only present when fetching with the label parameter. */
label?: string;
+ /** The exact prompt versions spliced into the returned content, in order of first appearance. Empty when the prompt has no references. Only present when references were resolved. */
+ resolved_references?: LLMPromptResolvedReference[];
created_at: string;
updated_at: string;
deleted: boolean;
@@ -105178,6 +105192,10 @@ export namespace Schemas {
* @maxLength 128
*/
label?: string;
+ /**
+ * Replace @@@prompt:...@@@ references with the referenced prompts' content before returning. Set to false to get the raw text with the reference tags, e.g. for editing or export. Only applies when content is 'full'.
+ */
+ resolve?: boolean;
/**
* Specific prompt version to fetch. If omitted, the latest version is returned.
* @minimum 1
diff --git a/services/mcp/src/generated/ai_observability/api.ts b/services/mcp/src/generated/ai_observability/api.ts
index 2cfff78ce33e..b9908e33273d 100644
--- a/services/mcp/src/generated/ai_observability/api.ts
+++ b/services/mcp/src/generated/ai_observability/api.ts
@@ -2163,6 +2163,8 @@ export const LlmPromptsNameRetrieveParams = () => zod.object({
export const llmPromptsNameRetrieveQueryContentDefault = `full`
export const llmPromptsNameRetrieveQueryLabelMax = 128
+export const llmPromptsNameRetrieveQueryResolveDefault = true
+
export const LlmPromptsNameRetrieveQueryParams = () => zod.object({
content: zod
.enum(['full', 'preview', 'none'])
@@ -2178,6 +2180,12 @@ export const LlmPromptsNameRetrieveQueryParams = () => zod.object({
.describe(
"Fetch the version this label currently points to, e.g. 'production'. Lowercase letters, numbers, dots, hyphens and underscores. Mutually exclusive with version."
),
+ resolve: zod
+ .boolean()
+ .default(llmPromptsNameRetrieveQueryResolveDefault)
+ .describe(
+ "Replace @@@prompt:...@@@ references with the referenced prompts' content before returning. Set to false to get the raw text with the reference tags, e.g. for editing or export. Only applies when content is 'full'."
+ ),
version: zod
.number()
.min(1)
diff --git a/services/mcp/src/tools/generated/ai_observability.ts b/services/mcp/src/tools/generated/ai_observability.ts
index a2e7e66d8720..ac10b6071a68 100644
--- a/services/mcp/src/tools/generated/ai_observability.ts
+++ b/services/mcp/src/tools/generated/ai_observability.ts
@@ -1477,6 +1477,7 @@ const llmaPromptGet = (): ToolBase<ReturnType<typeof LlmaPromptGetSchema>, Schem
query: {
content: params.content,
label: params.label,
+ resolve: params.resolve,
version: params.version,
},
})
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-prompt-get.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-prompt-get.json
index e75a3c04175c..08a8af9580d4 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-prompt-get.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-prompt-get.json
@@ -17,6 +17,11 @@
"pattern": "^[^/]+$",
"type": "string"
},
+ "resolve": {
+ "default": true,
+ "description": "Replace @@@prompt:...@@@ references with the referenced prompts' content before returning. Set to false to get the raw text with the reference tags, e.g. for editing or export. Only applies when content is 'full'.",
+ "type": "boolean"
+ },
"version": {
"description": "Specific prompt version to fetch. If omitted, the latest version is returned.",
"minimum": 1,
diff --git a/services/mcp/tests/unit/prompts-generated.test.ts b/services/mcp/tests/unit/prompts-generated.test.ts
index 2eebff67f2ec..2f2993f23ba5 100644
--- a/services/mcp/tests/unit/prompts-generated.test.ts
+++ b/services/mcp/tests/unit/prompts-generated.test.ts
@@ -26,14 +26,14 @@ describe('Generated llma-prompt-* tools', () => {
const tool = getToolByName(GENERATED_TOOLS, 'llma-prompt-get')
const parsed = tool.schema.parse({ prompt_name: 'checkout_prompt', version: 2 })
- expect(parsed).toEqual({ prompt_name: 'checkout_prompt', version: 2, content: 'full' })
+ expect(parsed).toEqual({ prompt_name: 'checkout_prompt', version: 2, content: 'full', resolve: true })
})
it('exposes content mode on the prompt-get schema so agents can fetch outline-only', () => {
const tool = getToolByName(GENERATED_TOOLS, 'llma-prompt-get')
const parsed = tool.schema.parse({ prompt_name: 'checkout_prompt', content: 'none' })
- expect(parsed).toEqual({ prompt_name: 'checkout_prompt', content: 'none' })
+ expect(parsed).toEqual({ prompt_name: 'checkout_prompt', content: 'none', resolve: true })
expect(() => tool.schema.parse({ prompt_name: 'checkout_prompt', content: 'bogus' })).toThrow()
})