mirror of
https://github.com/openai/codex.git
synced 2026-11-17 22:10:37 +00:00
Add a bundled skill for authoring MCP statuslines (#62036)
## What changed Add the explicitly invoked `create-statusline` skill with guidance for building, registering, and selecting a custom Codex CLI footer provider. Include a Python stdio MCP starter that renders the current thread's model and agent state from each resource read's snapshot. ## Testing Add a scenario snapshot for loading the bundled skill by name and a Python protocol test covering provider discovery, per-read snapshots, and Unicode text. GitOrigin-RevId: e48fd5064ad93bf37b50b5643028d4153a3b4f59
This commit is contained in:
@@ -273,6 +273,9 @@ mod frozen_cloud_skills;
|
||||
#[path = "scenarios_compaction_tests.rs"]
|
||||
mod compaction;
|
||||
|
||||
#[path = "scenarios_statusline_authoring_tests.rs"]
|
||||
mod statusline_authoring;
|
||||
|
||||
#[path = "scenarios_budget_context.rs"]
|
||||
mod budget_context;
|
||||
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
#![cfg(test)]
|
||||
//! Exercise an explicit request for the bundled statusline authoring skill.
|
||||
|
||||
use super::*;
|
||||
use core_test_support::responses::mount_sse_once;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn explicit_statusline_mention_loads_the_bundled_skill() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
let server = start_mock_server().await;
|
||||
let home = Arc::new(TempDir::new()?);
|
||||
fs::write(
|
||||
home.path().join("config.toml"),
|
||||
"[skills.bundled]\nenabled = true\n",
|
||||
)?;
|
||||
let mock = mount_sse_once(
|
||||
&server,
|
||||
sse(vec![
|
||||
ev_response_created("author"),
|
||||
ev_assistant_message("reply", "I'll show the current model in your footer."),
|
||||
ev_completed("author"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
let test = test_codex()
|
||||
.with_model("gpt-6-astra")
|
||||
.with_home(home)
|
||||
.with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing())
|
||||
.with_extensions(skills_extensions())
|
||||
.with_config(configure_scenario_catalog)
|
||||
.build_with_auto_env(&server)
|
||||
.await?;
|
||||
|
||||
test.submit_text_turn("Use $create-statusline to make a footer showing my current model.")
|
||||
.await?;
|
||||
|
||||
let request = mock.single_request();
|
||||
assert!(
|
||||
request
|
||||
.message_input_texts("developer")
|
||||
.iter()
|
||||
.all(|message| !message.contains("- create-statusline:"))
|
||||
);
|
||||
insta::assert_snapshot!(context_snapshot::format_request_history_snapshot(
|
||||
"A user requests the bundled statusline skill by name.",
|
||||
&mock.requests(),
|
||||
&ContextSnapshotOptions::default().rewrite_known_segments(),
|
||||
));
|
||||
Ok(())
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
---
|
||||
source: core/tests/suite/scenarios_statusline_authoring_tests.rs
|
||||
expression: "context_snapshot::format_request_history_snapshot(\"A user requests the bundled statusline skill by name.\",\n&mock.requests(),\n&ContextSnapshotOptions::default().rewrite_known_segments(),)"
|
||||
---
|
||||
Scenario: A user requests the bundled statusline skill by name.
|
||||
|
||||
## Window 1
|
||||
-- request 1 (turn) --
|
||||
00:additional_tools/developer (3; hash=e43eac769da0e93e):
|
||||
- namespace/functions; hash=81846de5bc4e7474
|
||||
- custom/exec
|
||||
- function/wait
|
||||
- function/request_user_input
|
||||
- function/request_user_input_async
|
||||
- namespace/clock: Tools for reading and waiting on time.; hash=f402e8c5e9b5e317
|
||||
- function/sleep
|
||||
- namespace/collaboration: Tools for spawning and managing sub-agents.; hash=2c8d6295978dbe63
|
||||
- function/followup_task
|
||||
- function/interrupt_agent
|
||||
- function/list_agents
|
||||
- function/send_message
|
||||
- function/spawn_agent
|
||||
- function/wait_agent
|
||||
01:message/developer:
|
||||
<MODEL_INSTRUCTIONS>
|
||||
02:message/developer[3]:
|
||||
[01] <SKILLS_INSTRUCTIONS>
|
||||
[02] <PERMISSIONS_INSTRUCTIONS>
|
||||
[03] <COLLABORATION_MODE>
|
||||
03:message/developer:
|
||||
<MULTI_AGENT_ROLE>
|
||||
04:message/developer:
|
||||
<MULTI_AGENT_MODE>
|
||||
05:message/user:
|
||||
<ENVIRONMENT_CONTEXT>
|
||||
06:message/user:
|
||||
Use $create-statusline to make a footer showing my current model.
|
||||
07:message/user:
|
||||
<skill>
|
||||
<name>create-statusline</name>
|
||||
<path><SKILLS_ROOT>/.system/create-statusline/SKILL.md</path>
|
||||
---
|
||||
name: create-statusline
|
||||
description: Build and enable a custom MCP statusline for the Codex CLI. Use when someone wants a provider that displays information in the terminal footer.
|
||||
---
|
||||
|
||||
<OMITTED 9 LINES; ~409 TOKENS; hash=9f5b7f7878d50218>
|
||||
|
||||
### Enable and verify
|
||||
|
||||
Install the provider through an installed plugin or register the stdio command on the connected app-serv...guration and restart the TUI if you changed the flag. [hash=42c056811162cca2]
|
||||
|
||||
Exercise `tools/list` and `resources/read` with a representative snapshot. After adding the server, star... file, restart its stdio process to load the changes. [hash=0c36ed73eb177796]
|
||||
|
||||
</skill>
|
||||
08:configuration_update:reasoning={"effort":"low"}
|
||||
@@ -0,0 +1,20 @@
|
||||
---
|
||||
name: create-statusline
|
||||
description: Build and enable a custom MCP statusline for the Codex CLI. Use when someone wants a provider that displays information in the terminal footer.
|
||||
---
|
||||
|
||||
Help the user choose what to show. Reuse an existing stdio MCP server when it already owns the data and is configured globally or supplied by an installed plugin. For a new provider, copy [the Python starter](assets/statusline.py) and edit `render`. The [TypeScript reference](references/statusline.d.ts) bundled with this skill describes the snapshot and UI tree. If those files are on a different machine from your workspace, write the provider in the workspace using the protocol below.
|
||||
|
||||
### Advertise and render the footer
|
||||
|
||||
Advertise exactly one valid statusline entrypoint per tool in `tools/list`. Use the stable server and tool names for the saved selection. Set `_meta["openai/ui"].entrypoints` to include `{"type":"statusline","resourceUri":"ui://my-statusline/footer"}`. The tool's title is the label in the picker.
|
||||
|
||||
Codex requests the advertised URI with `resources/read`. Read the displayed thread's snapshot from `params._meta["com.openai/codex-statusline-state"]`. Return exactly one text resource at that URI, with MIME type `application/json` and a JSON-encoded UI tree. Optional account and usage fields may be absent. A string renders literal text and `null` clears the footer.
|
||||
|
||||
Use a `row` with an explicit whole-number `gap` to group items. Use named theme or status colors to follow the user's theme. Codex accepts up to 64 KiB of UI tree JSON, 16 KiB of UTF-8 leaf text, 256 non-null nodes, and a depth of 16 (root at 0). Each read has one second to finish. After a successful read, Codex waits one second before reading again. An error or timeout stops polling. Reselect the provider in `/statusline` to restart it.
|
||||
|
||||
### Enable and verify
|
||||
|
||||
Install the provider through an installed plugin or register the stdio command on the connected app-server host. For example, run `codex mcp add my-statusline -- python3 -u /absolute/path/to/statusline.py` there, using a path and interpreter the host can access. If the workspace is on a separate executor, give the user the provider file to copy to the host and the command to run there. Set `tui_extensions_statusline = true` under `[features]` in the TUI client's configuration and restart the TUI if you changed the flag.
|
||||
|
||||
Exercise `tools/list` and `resources/read` with a representative snapshot. After adding the server, start a new conversation in its workspace to connect to it. Open `/statusline`, choose **Choose a statusline plugin**, and select the provider. Verify that changing threads changes the displayed inputs. F2 shows the failed attempt if the footer falls back. After editing the Python file, restart its stdio process to load the changes.
|
||||
@@ -0,0 +1,2 @@
|
||||
policy:
|
||||
allow_implicit_invocation: false
|
||||
@@ -0,0 +1,96 @@
|
||||
"""A Codex statusline provider using newline-delimited MCP over stdio."""
|
||||
|
||||
import json
|
||||
import sys
|
||||
|
||||
|
||||
URI = "ui://my-statusline/footer"
|
||||
TOOL = {
|
||||
"name": "statusline",
|
||||
"title": "My statusline",
|
||||
"description": "Show the current model and agent state in the Codex footer.",
|
||||
"inputSchema": {"type": "object", "properties": {}},
|
||||
"_meta": {
|
||||
"openai/ui": {"entrypoints": [{"type": "statusline", "resourceUri": URI}]}
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def render(state):
|
||||
"""Return the UI tree for this resource read's thread."""
|
||||
thread = state.get("thread", {})
|
||||
model = thread.get("model", {}).get("display_name") or "Codex"
|
||||
children = [
|
||||
{"type": "text", "props": {"color": "status-model"}, "children": [model]}
|
||||
]
|
||||
if agent_state := thread.get("agent", {}).get("state"):
|
||||
children.append({"type": "italic", "children": [agent_state]})
|
||||
return {"type": "row", "props": {"gap": 1, "wrap": "wrap"}, "children": children}
|
||||
|
||||
|
||||
def respond(method, params):
|
||||
if method == "initialize":
|
||||
return {
|
||||
"protocolVersion": "2025-06-18",
|
||||
"capabilities": {"tools": {}, "resources": {}},
|
||||
"serverInfo": {"name": "my-statusline", "version": "1.0"},
|
||||
}
|
||||
if method == "ping":
|
||||
return {}
|
||||
if method == "tools/list":
|
||||
return {"tools": [TOOL]}
|
||||
if method == "tools/call":
|
||||
if params.get("name") != TOOL["name"]:
|
||||
raise ValueError("Unknown tool name")
|
||||
return {
|
||||
"content": [{"type": "text", "text": f"The statusline resource is {URI}."}]
|
||||
}
|
||||
if method == "resources/list":
|
||||
return {
|
||||
"resources": [
|
||||
{"name": "footer", "uri": URI, "mimeType": "application/json"}
|
||||
]
|
||||
}
|
||||
if method == "resources/templates/list":
|
||||
return {"resourceTemplates": []}
|
||||
if method == "resources/read":
|
||||
if params.get("uri") != URI:
|
||||
raise ValueError("Unknown resource URI")
|
||||
state = params.get("_meta", {}).get("com.openai/codex-statusline-state", {})
|
||||
return {
|
||||
"contents": [
|
||||
{
|
||||
"uri": URI,
|
||||
"mimeType": "application/json",
|
||||
"text": json.dumps(render(state), ensure_ascii=False),
|
||||
}
|
||||
]
|
||||
}
|
||||
raise KeyError(method)
|
||||
|
||||
|
||||
def main():
|
||||
for line in sys.stdin.buffer:
|
||||
reply = {"jsonrpc": "2.0", "id": None}
|
||||
try:
|
||||
request = json.loads(line)
|
||||
if not isinstance(request, dict) or not isinstance(
|
||||
request.get("method"), str
|
||||
):
|
||||
reply["error"] = {"code": -32600, "message": "Invalid request"}
|
||||
elif "id" not in request:
|
||||
continue
|
||||
else:
|
||||
reply["id"] = request["id"]
|
||||
reply["result"] = respond(request["method"], request.get("params", {}))
|
||||
except json.JSONDecodeError:
|
||||
reply["error"] = {"code": -32700, "message": "Parse error"}
|
||||
except KeyError:
|
||||
reply["error"] = {"code": -32601, "message": "Method not found"}
|
||||
except (TypeError, ValueError, AttributeError):
|
||||
reply["error"] = {"code": -32602, "message": "Invalid parameters"}
|
||||
print(json.dumps(reply), flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,92 @@
|
||||
"""Exercise the shipped statusline starter through its stdio protocol."""
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
|
||||
STARTER = (
|
||||
Path(__file__).resolve().parents[1]
|
||||
/ "src/assets/samples/create-statusline/assets/statusline.py"
|
||||
)
|
||||
|
||||
|
||||
class StatuslineStarterTest(unittest.TestCase):
|
||||
def test_advertised_resource_uses_each_reads_snapshot(self):
|
||||
def exchange(*messages):
|
||||
wire = "".join(
|
||||
json.dumps({"jsonrpc": "2.0", **message}, ensure_ascii=False) + "\n"
|
||||
for message in messages
|
||||
)
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-u", str(STARTER)],
|
||||
input=wire,
|
||||
capture_output=True,
|
||||
encoding="utf-8",
|
||||
check=True,
|
||||
timeout=10,
|
||||
env={**os.environ, "PYTHONIOENCODING": "ascii"},
|
||||
)
|
||||
replies = [json.loads(line) for line in result.stdout.splitlines()]
|
||||
self.assertEqual(
|
||||
[reply["id"] for reply in replies],
|
||||
[message["id"] for message in messages if "id" in message],
|
||||
)
|
||||
return [reply["result"] for reply in replies]
|
||||
|
||||
handshake = (
|
||||
{
|
||||
"id": 1,
|
||||
"method": "initialize",
|
||||
"params": {"protocolVersion": "2025-06-18"},
|
||||
},
|
||||
{"method": "notifications/initialized"},
|
||||
)
|
||||
initialized, listed = exchange(*handshake, {"id": 2, "method": "tools/list"})
|
||||
for capability in ("tools", "resources"):
|
||||
self.assertIn(capability, initialized["capabilities"])
|
||||
(tool,) = listed["tools"]
|
||||
(entry,) = tool["_meta"]["openai/ui"]["entrypoints"]
|
||||
self.assertEqual(entry["type"], "statusline")
|
||||
uri = entry["resourceUri"]
|
||||
self.assertTrue(uri.startswith("ui://"))
|
||||
|
||||
samples = [("Model A", "working"), ("Modèle 曲", "ready")]
|
||||
reads = []
|
||||
for request_id, (model, activity) in enumerate(samples, start=2):
|
||||
state = {
|
||||
"thread": {
|
||||
"model": {"display_name": model},
|
||||
"agent": {"state": activity},
|
||||
}
|
||||
}
|
||||
reads.append(
|
||||
{
|
||||
"id": request_id,
|
||||
"method": "resources/read",
|
||||
"params": {
|
||||
"uri": uri,
|
||||
"_meta": {"com.openai/codex-statusline-state": state},
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
def leaves(node):
|
||||
if isinstance(node, str):
|
||||
yield node
|
||||
elif node is not None:
|
||||
for child in node["children"]:
|
||||
yield from leaves(child)
|
||||
|
||||
_, *replies = exchange(*handshake, *reads)
|
||||
for reply, expected in zip(replies, samples, strict=True):
|
||||
(item,) = reply["contents"]
|
||||
self.assertEqual((item["uri"], item["mimeType"]), (uri, "application/json"))
|
||||
self.assertEqual(tuple(leaves(json.loads(item["text"]))), expected)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user