chore: import upstream snapshot with attribution
Deploy Docs / deploy-docs (push) Failing after 1s
Conformance Tests / client-conformance (push) Failing after 3s
Conformance Tests / server-conformance (push) Failing after 1s
GitHub Actions Security Analysis / zizmor (push) Failing after 1s
CI / checks (push) Failing after 59m20s
CI / all-green (push) Has been cancelled
Deploy Docs / deploy-docs (push) Failing after 1s
Conformance Tests / client-conformance (push) Failing after 3s
Conformance Tests / server-conformance (push) Failing after 1s
GitHub Actions Security Analysis / zizmor (push) Failing after 1s
CI / checks (push) Failing after 59m20s
CI / all-green (push) Has been cancelled
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
# prompts
|
||||
|
||||
Expose prompt templates with `@mcp.prompt()` and let clients autocomplete their
|
||||
arguments with `@mcp.completion()`. `MCPServer` derives each prompt's
|
||||
`arguments` (name + required) from the function signature. The client lists
|
||||
prompts, completes the `language` argument of `code_review`, then renders both
|
||||
prompts.
|
||||
|
||||
## Run it
|
||||
|
||||
```bash
|
||||
# stdio (default — the client spawns the server as a subprocess)
|
||||
uv run python -m stories.prompts.client
|
||||
|
||||
# HTTP — the client self-hosts the server on a free port, runs, then tears it down
|
||||
uv run python -m stories.prompts.client --http
|
||||
# same, against the lowlevel-API server variant
|
||||
uv run python -m stories.prompts.client --http --server server_lowlevel
|
||||
```
|
||||
|
||||
## What to look at
|
||||
|
||||
- `client.py` `main` — the body opens with `async with Client(target,
|
||||
mode=mode) as client:`; `target` is anything `Client(...)` accepts (an
|
||||
in-process server, a `Transport`, or an HTTP URL).
|
||||
- `server.py` `greet` vs `code_review` — return a bare `str` (wrapped as one
|
||||
user message) or a `list[Message]` for a multi-turn seed conversation.
|
||||
- `server.py` `complete()` — one global handler dispatches on `ref` +
|
||||
`argument.name`; returning `None` becomes an empty completion. There is no
|
||||
per-argument `completer=` sugar yet.
|
||||
- `server_lowlevel.py` — the same `Prompt` / `PromptArgument` descriptors and
|
||||
`GetPromptResult` built by hand; this is what `MCPServer` generates for you.
|
||||
- `client.py` `complete(...)` — `argument` is a `{"name": ..., "value": ...}`
|
||||
dict, the only `Client` request method that takes a raw dict for a typed
|
||||
wire field.
|
||||
|
||||
## Caveats
|
||||
|
||||
`@mcp.prompt()` and `@mcp.completion()` need the parentheses — `@mcp.prompt`
|
||||
without `()` raises a confusing `TypeError` at registration time.
|
||||
|
||||
## Spec
|
||||
|
||||
[Prompts](https://modelcontextprotocol.io/specification/2025-11-25/server/prompts)
|
||||
· [Completion](https://modelcontextprotocol.io/specification/2025-11-25/server/utilities/completion)
|
||||
|
||||
## See also
|
||||
|
||||
`tools/` (start here), `resources/` (the other `ref` kind completion accepts),
|
||||
`pagination/` (`list_prompts` cursor loop).
|
||||
@@ -0,0 +1,39 @@
|
||||
"""List prompts, autocomplete an argument, then render both prompts."""
|
||||
|
||||
from mcp_types import PromptReference, TextContent
|
||||
|
||||
from mcp.client import Client
|
||||
from stories._harness import Target, run_client
|
||||
|
||||
|
||||
async def main(target: Target, *, mode: str = "auto") -> None:
|
||||
async with Client(target, mode=mode) as client:
|
||||
listed = await client.list_prompts()
|
||||
by_name = {p.name: p for p in listed.prompts}
|
||||
assert set(by_name) == {"greet", "code_review"}
|
||||
assert by_name["greet"].arguments is not None
|
||||
assert [a.name for a in by_name["greet"].arguments] == ["name"]
|
||||
assert by_name["greet"].arguments[0].required is True
|
||||
assert by_name["code_review"].title == "Code Review"
|
||||
|
||||
completion = await client.complete(
|
||||
PromptReference(name="code_review"),
|
||||
argument={"name": "language", "value": "py"},
|
||||
)
|
||||
assert completion.completion.values == ["python", "pytorch"], completion
|
||||
|
||||
greeted = await client.get_prompt("greet", {"name": "Ada"})
|
||||
assert len(greeted.messages) == 1
|
||||
assert greeted.messages[0].role == "user"
|
||||
assert isinstance(greeted.messages[0].content, TextContent)
|
||||
assert "Ada" in greeted.messages[0].content.text
|
||||
|
||||
reviewed = await client.get_prompt("code_review", {"language": "rust", "code": "fn main() {}"})
|
||||
assert [m.role for m in reviewed.messages] == ["user", "assistant"]
|
||||
first = reviewed.messages[0].content
|
||||
assert isinstance(first, TextContent)
|
||||
assert "rust" in first.text and "fn main() {}" in first.text
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_client(main)
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Prompts primitive: register templates, list, render, complete an argument."""
|
||||
|
||||
from mcp_types import Completion, CompletionArgument, CompletionContext, PromptReference, ResourceTemplateReference
|
||||
|
||||
from mcp.server.mcpserver import MCPServer
|
||||
from mcp.server.mcpserver.prompts.base import AssistantMessage, Message, UserMessage
|
||||
from stories._hosting import run_server_from_args
|
||||
|
||||
LANGUAGES = ["python", "pytorch", "rust", "go", "typescript"]
|
||||
|
||||
|
||||
def build_server() -> MCPServer:
|
||||
mcp = MCPServer("prompts-example")
|
||||
|
||||
@mcp.prompt(title="Greeting")
|
||||
def greet(name: str) -> str:
|
||||
"""Ask the model to greet someone by name."""
|
||||
return f"Write a one-line greeting for {name}."
|
||||
|
||||
@mcp.prompt(title="Code Review")
|
||||
def code_review(language: str, code: str) -> list[Message]:
|
||||
"""Ask the model to review a code snippet."""
|
||||
return [
|
||||
UserMessage(f"Review this {language} code for bugs and idioms:\n\n{code}"),
|
||||
AssistantMessage("I'll review it. Let me read through the code first."),
|
||||
]
|
||||
|
||||
@mcp.completion()
|
||||
async def complete(
|
||||
ref: PromptReference | ResourceTemplateReference,
|
||||
argument: CompletionArgument,
|
||||
context: CompletionContext | None,
|
||||
) -> Completion | None:
|
||||
if isinstance(ref, PromptReference) and ref.name == "code_review" and argument.name == "language":
|
||||
matches = [lang for lang in LANGUAGES if lang.startswith(argument.value)]
|
||||
return Completion(values=matches, total=len(matches), has_more=False)
|
||||
return None
|
||||
|
||||
return mcp
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_server_from_args(build_server)
|
||||
@@ -0,0 +1,87 @@
|
||||
"""Prompts primitive (lowlevel API): hand-built Prompt descriptors, GetPromptResult, completion."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
import mcp_types as types
|
||||
|
||||
from mcp.server.context import ServerRequestContext
|
||||
from mcp.server.lowlevel import Server
|
||||
from stories._hosting import run_server_from_args
|
||||
|
||||
LANGUAGES = ["python", "pytorch", "rust", "go", "typescript"]
|
||||
|
||||
PROMPTS = [
|
||||
types.Prompt(
|
||||
name="greet",
|
||||
title="Greeting",
|
||||
description="Ask the model to greet someone by name.",
|
||||
arguments=[types.PromptArgument(name="name", required=True)],
|
||||
),
|
||||
types.Prompt(
|
||||
name="code_review",
|
||||
title="Code Review",
|
||||
description="Ask the model to review a code snippet.",
|
||||
arguments=[
|
||||
types.PromptArgument(name="language", required=True),
|
||||
types.PromptArgument(name="code", required=True),
|
||||
],
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def build_server() -> Server[Any]:
|
||||
async def list_prompts(
|
||||
ctx: ServerRequestContext[Any], params: types.PaginatedRequestParams | None
|
||||
) -> types.ListPromptsResult:
|
||||
return types.ListPromptsResult(prompts=PROMPTS)
|
||||
|
||||
async def get_prompt(ctx: ServerRequestContext[Any], params: types.GetPromptRequestParams) -> types.GetPromptResult:
|
||||
args = params.arguments or {}
|
||||
if params.name == "greet":
|
||||
return types.GetPromptResult(
|
||||
description="Ask the model to greet someone by name.",
|
||||
messages=[
|
||||
types.PromptMessage(
|
||||
role="user",
|
||||
content=types.TextContent(text=f"Write a one-line greeting for {args['name']}."),
|
||||
)
|
||||
],
|
||||
)
|
||||
if params.name == "code_review":
|
||||
return types.GetPromptResult(
|
||||
description="Ask the model to review a code snippet.",
|
||||
messages=[
|
||||
types.PromptMessage(
|
||||
role="user",
|
||||
content=types.TextContent(
|
||||
text=f"Review this {args['language']} code for bugs and idioms:\n\n{args['code']}"
|
||||
),
|
||||
),
|
||||
types.PromptMessage(
|
||||
role="assistant",
|
||||
content=types.TextContent(text="I'll review it. Let me read through the code first."),
|
||||
),
|
||||
],
|
||||
)
|
||||
raise NotImplementedError
|
||||
|
||||
async def completion(ctx: ServerRequestContext[Any], params: types.CompleteRequestParams) -> types.CompleteResult:
|
||||
if (
|
||||
isinstance(params.ref, types.PromptReference)
|
||||
and params.ref.name == "code_review"
|
||||
and params.argument.name == "language"
|
||||
):
|
||||
matches = [lang for lang in LANGUAGES if lang.startswith(params.argument.value)]
|
||||
return types.CompleteResult(completion=types.Completion(values=matches, total=len(matches), has_more=False))
|
||||
return types.CompleteResult(completion=types.Completion(values=[]))
|
||||
|
||||
return Server(
|
||||
"prompts-example",
|
||||
on_list_prompts=list_prompts,
|
||||
on_get_prompt=get_prompt,
|
||||
on_completion=completion,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_server_from_args(build_server)
|
||||
Reference in New Issue
Block a user