Refactor context API to standardize property naming conventions

- Changed property names from `MCP` to `mcp` and `Trace` to `trace` in the Context object for consistency with JavaScript naming conventions.
- Updated related tests and documentation to reflect these changes, ensuring clarity and uniformity across the API.
- Enhanced examples in JSAPI.md to demonstrate the new property names, improving developer guidance.
This commit is contained in:
Max 2025-12-09 19:10:06 +08:00
parent 2f1c7063c1
commit 98d0d749ed
6 changed files with 94 additions and 94 deletions

View file

@ -36,8 +36,8 @@ interface Context {
// Objects
space: Space; // Shared data space for passing data between requests
Trace: Trace; // Trace object for debugging and monitoring
MCP: MCP; // MCP object for external tool/resource access
trace: Trace; // Trace object for debugging and monitoring
mcp: MCP; // MCP object for external tool/resource access
}
```
@ -899,7 +899,7 @@ function Create(ctx, messages) {
// MCP tool call block
ctx.Send("Fetching data...", mcp_block);
const data = ctx.MCP.CallTool("tool", "method", {});
const data = ctx.mcp.CallTool("tool", "method", {});
ctx.Send(`Found ${data.length} results`, mcp_block);
ctx.EndBlock(mcp_block);
@ -926,11 +926,11 @@ try {
## Trace API
The `ctx.Trace` object provides comprehensive tracing capabilities for debugging and monitoring agent execution.
The `ctx.trace` object provides comprehensive tracing capabilities for debugging and monitoring agent execution.
### Node Operations
#### `ctx.Trace.Add(input, options)`
#### `ctx.trace.Add(input, options)`
Creates a new trace node (sequential step).
@ -954,7 +954,7 @@ interface TraceNodeOption {
**Example:**
```javascript
const search_node = ctx.Trace.Add(
const search_node = ctx.trace.Add(
{ query: "What is AI?" },
{
label: "Search Query",
@ -965,7 +965,7 @@ const search_node = ctx.Trace.Add(
);
```
#### `ctx.Trace.Parallel(inputs)`
#### `ctx.trace.Parallel(inputs)`
Creates multiple parallel trace nodes for concurrent operations.
@ -985,7 +985,7 @@ interface ParallelInput {
**Example:**
```javascript
const parallel_nodes = ctx.Trace.Parallel([
const parallel_nodes = ctx.trace.Parallel([
{
input: { url: "https://api1.com" },
option: {
@ -1013,16 +1013,16 @@ Add log entries to the current trace node:
```javascript
// Information logs
ctx.Trace.Info("Processing started", { step: 1 });
ctx.trace.Info("Processing started", { step: 1 });
// Debug logs
ctx.Trace.Debug("Variable value", { value: 42 });
ctx.trace.Debug("Variable value", { value: 42 });
// Warning logs
ctx.Trace.Warn("Deprecated feature used", { feature: "old_api" });
ctx.trace.Warn("Deprecated feature used", { feature: "old_api" });
// Error logs
ctx.Trace.Error("Operation failed", { error: "timeout" });
ctx.trace.Error("Operation failed", { error: "timeout" });
```
### Node Status Operations
@ -1032,7 +1032,7 @@ ctx.Trace.Error("Operation failed", { error: "timeout" });
Sets the output data for a node.
```javascript
const search_node = ctx.Trace.Add({ query: "search" }, options);
const search_node = ctx.trace.Add({ query: "search" }, options);
search_node.SetOutput({ results: [...] });
```
@ -1067,39 +1067,39 @@ try {
### Query Operations
#### `ctx.Trace.GetRootNode()`
#### `ctx.trace.GetRootNode()`
Returns the root node of the trace tree.
```javascript
const root_node = ctx.Trace.GetRootNode();
const root_node = ctx.trace.GetRootNode();
console.log(root_node.id, root_node.label);
```
#### `ctx.Trace.GetNode(id)`
#### `ctx.trace.GetNode(id)`
Retrieves a specific node by ID.
```javascript
const target_node = ctx.Trace.GetNode("node-123");
const target_node = ctx.trace.GetNode("node-123");
```
#### `ctx.Trace.GetCurrentNodes()`
#### `ctx.trace.GetCurrentNodes()`
Returns the current active nodes (may be multiple if in parallel state).
```javascript
const current_nodes = ctx.Trace.GetCurrentNodes();
const current_nodes = ctx.trace.GetCurrentNodes();
```
### Memory Space Operations
#### `ctx.Trace.CreateSpace(option)`
#### `ctx.trace.CreateSpace(option)`
Creates a memory space for storing key-value data.
```javascript
const memory_space = ctx.Trace.CreateSpace({
const memory_space = ctx.trace.CreateSpace({
label: "Context Memory",
type: "context",
icon: "database",
@ -1107,38 +1107,38 @@ const memory_space = ctx.Trace.CreateSpace({
});
```
#### `ctx.Trace.GetSpace(id)`
#### `ctx.trace.GetSpace(id)`
Retrieves a memory space by ID.
```javascript
const context_space = ctx.Trace.GetSpace("context");
const context_space = ctx.trace.GetSpace("context");
```
#### `ctx.Trace.HasSpace(id)`
#### `ctx.trace.HasSpace(id)`
Checks if a memory space exists.
```javascript
if (ctx.Trace.HasSpace("context")) {
if (ctx.trace.HasSpace("context")) {
// Space exists
}
```
#### `ctx.Trace.DeleteSpace(id)`
#### `ctx.trace.DeleteSpace(id)`
Deletes a memory space.
```javascript
ctx.Trace.DeleteSpace("temp_storage");
ctx.trace.DeleteSpace("temp_storage");
```
#### `ctx.Trace.ListSpaces()`
#### `ctx.trace.ListSpaces()`
Lists all memory spaces.
```javascript
const all_spaces = ctx.Trace.ListSpaces();
const all_spaces = ctx.trace.ListSpaces();
all_spaces.forEach((space) => {
console.log(space.id, space.label);
});
@ -1270,24 +1270,24 @@ function Next(ctx, payload) {
## MCP API
The `ctx.MCP` object provides access to Model Context Protocol operations for interacting with external tools, resources, and prompts.
The `ctx.mcp` object provides access to Model Context Protocol operations for interacting with external tools, resources, and prompts.
### Resource Operations
#### `ctx.MCP.ListResources(client)`
#### `ctx.mcp.ListResources(client)`
Lists available resources from an MCP client.
```javascript
const fs_resources = ctx.MCP.ListResources("filesystem");
const fs_resources = ctx.mcp.ListResources("filesystem");
```
#### `ctx.MCP.ReadResource(client, uri)`
#### `ctx.mcp.ReadResource(client, uri)`
Reads a specific resource.
```javascript
const file_content = ctx.MCP.ReadResource(
const file_content = ctx.mcp.ReadResource(
"filesystem",
"file:///path/to/file.txt"
);
@ -1295,42 +1295,42 @@ const file_content = ctx.MCP.ReadResource(
### Tool Operations
#### `ctx.MCP.ListTools(client)`
#### `ctx.mcp.ListTools(client)`
Lists available tools from an MCP client.
```javascript
const available_tools = ctx.MCP.ListTools("toolkit");
const available_tools = ctx.mcp.ListTools("toolkit");
```
#### `ctx.MCP.CallTool(client, name, args)`
#### `ctx.mcp.CallTool(client, name, args)`
Calls a single tool.
```javascript
const calc_result = ctx.MCP.CallTool("calculator", "add", {
const calc_result = ctx.mcp.CallTool("calculator", "add", {
a: 10,
b: 32,
});
```
#### `ctx.MCP.CallTools(client, calls)`
#### `ctx.mcp.CallTools(client, calls)`
Calls multiple tools sequentially.
```javascript
const tool_results = ctx.MCP.CallTools("toolkit", [
const tool_results = ctx.mcp.CallTools("toolkit", [
{ name: "tool1", args: { param: "value1" } },
{ name: "tool2", args: { param: "value2" } },
]);
```
#### `ctx.MCP.CallToolsParallel(client, calls)`
#### `ctx.mcp.CallToolsParallel(client, calls)`
Calls multiple tools in parallel.
```javascript
const parallel_results = ctx.MCP.CallToolsParallel("toolkit", [
const parallel_results = ctx.mcp.CallToolsParallel("toolkit", [
{ name: "api1", args: { endpoint: "/users" } },
{ name: "api2", args: { endpoint: "/posts" } },
]);
@ -1338,32 +1338,32 @@ const parallel_results = ctx.MCP.CallToolsParallel("toolkit", [
### Prompt Operations
#### `ctx.MCP.ListPrompts(client)`
#### `ctx.mcp.ListPrompts(client)`
Lists available prompts from an MCP client.
```javascript
const available_prompts = ctx.MCP.ListPrompts("prompt_library");
const available_prompts = ctx.mcp.ListPrompts("prompt_library");
```
#### `ctx.MCP.GetPrompt(client, name, args?)`
#### `ctx.mcp.GetPrompt(client, name, args?)`
Retrieves a specific prompt.
```javascript
const review_prompt = ctx.MCP.GetPrompt("prompt_library", "code_review", {
const review_prompt = ctx.mcp.GetPrompt("prompt_library", "code_review", {
language: "javascript",
});
```
### Sample Operations
#### `ctx.MCP.CreateSample(client, uri, sample)`
#### `ctx.mcp.CreateSample(client, uri, sample)`
Creates a sample for a resource.
```javascript
ctx.MCP.CreateSample("filesystem", "file:///examples", {
ctx.mcp.CreateSample("filesystem", "file:///examples", {
name: "example1",
content: "Sample content",
});
@ -1566,7 +1566,7 @@ function Create(ctx, messages) {
ctx.space.Set("original_query", messages[0]?.content || "");
// Add trace node
ctx.Trace.Add(
ctx.trace.Add(
{ messages },
{
label: "Create Hook",
@ -1596,7 +1596,7 @@ function Next(ctx, payload) {
const original_query = ctx.space.Get("original_query");
// Create trace node for custom processing
const process_node = ctx.Trace.Add(
const process_node = ctx.trace.Add(
{ completion, tools },
{
label: "Custom Processing",
@ -1606,7 +1606,7 @@ function Next(ctx, payload) {
}
);
ctx.Trace.Info("Starting custom processing", {
ctx.trace.Info("Starting custom processing", {
original_query: original_query,
tool_count: tools?.length || 0,
});
@ -1615,7 +1615,7 @@ function Next(ctx, payload) {
const msg_id = ctx.SendStream("# Search Results\n\n");
// Call MCP tool for additional data
const search_results = ctx.MCP.CallTool("search_engine", "search", {
const search_results = ctx.mcp.CallTool("search_engine", "search", {
query: "latest AI news",
limit: 5,
});
@ -1640,7 +1640,7 @@ function Next(ctx, payload) {
metadata: { processed: true },
};
} catch (error) {
ctx.Trace.Error("Processing failed", { error: error.message });
ctx.trace.Error("Processing failed", { error: error.message });
throw error;
}
}
@ -1666,7 +1666,7 @@ All Context methods throw exceptions on failure. Always handle errors appropriat
try {
ctx.Send(message);
} catch (error) {
ctx.Trace.Error("Failed to send message", { error: error.message });
ctx.trace.Error("Failed to send message", { error: error.message });
throw error;
}
```

View file

@ -59,8 +59,8 @@ func (ctx *Context) NewObject(v8ctx *v8go.Context) (*v8go.Value, error) {
// Lifecycle methods
jsObject.Set("EndBlock", ctx.endBlockMethod(v8ctx.Isolate()))
// Set MCP object
jsObject.Set("MCP", ctx.newMCPObject(v8ctx.Isolate()))
// Set mcp object
jsObject.Set("mcp", ctx.newMCPObject(v8ctx.Isolate()))
// Note: Space object will be set after instance creation (requires v8ctx)
@ -86,11 +86,11 @@ func (ctx *Context) NewObject(v8ctx *v8go.Context) (*v8go.Value, error) {
return nil, err
}
// Set Trace object (property, not method)
// Set trace object (property, not method)
// If trace is not initialized, use no-op object
traceObj := ctx.createTraceObject(v8ctx)
if traceObj != nil {
obj.Set("Trace", traceObj)
obj.Set("trace", traceObj)
}
// Set complex objects (maps, arrays) after instance creation using bridge

View file

@ -30,7 +30,7 @@ func TestMCPListResources(t *testing.T) {
res, err := v8.Call(v8.CallOptions{}, `
function test(ctx) {
// List resources from echo MCP
const result = ctx.MCP.ListResources("echo", "")
const result = ctx.mcp.ListResources("echo", "")
if (!result || !result.resources) {
throw new Error("Expected resources")
@ -75,7 +75,7 @@ func TestMCPReadResource(t *testing.T) {
res, err := v8.Call(v8.CallOptions{}, `
function test(ctx) {
// Read info resource
const result = ctx.MCP.ReadResource("echo", "echo://info")
const result = ctx.mcp.ReadResource("echo", "echo://info")
if (!result || !result.contents) {
throw new Error("Expected contents")
@ -118,7 +118,7 @@ func TestMCPListTools(t *testing.T) {
res, err := v8.Call(v8.CallOptions{}, `
function test(ctx) {
// List tools from echo MCP
const result = ctx.MCP.ListTools("echo", "")
const result = ctx.mcp.ListTools("echo", "")
if (!result || !result.tools) {
throw new Error("Expected tools")
@ -165,7 +165,7 @@ func TestMCPCallTool(t *testing.T) {
res, err := v8.Call(v8.CallOptions{}, `
function test(ctx) {
// Call ping tool
const result = ctx.MCP.CallTool("echo", "ping", { count: 3, message: "test" })
const result = ctx.mcp.CallTool("echo", "ping", { count: 3, message: "test" })
if (!result || !result.content) {
throw new Error("Expected content")
@ -213,7 +213,7 @@ func TestMCPCallTools(t *testing.T) {
{ name: "status", arguments: { verbose: false } }
]
const result = ctx.MCP.CallTools("echo", tools)
const result = ctx.mcp.CallTools("echo", tools)
if (!result || !result.results) {
throw new Error("Expected results")
@ -261,7 +261,7 @@ func TestMCPCallToolsParallel(t *testing.T) {
{ name: "status", arguments: { verbose: true } }
]
const result = ctx.MCP.CallToolsParallel("echo", tools)
const result = ctx.mcp.CallToolsParallel("echo", tools)
if (!result || !result.results) {
throw new Error("Expected results")
@ -304,7 +304,7 @@ func TestMCPListPrompts(t *testing.T) {
res, err := v8.Call(v8.CallOptions{}, `
function test(ctx) {
// List prompts from echo MCP
const result = ctx.MCP.ListPrompts("echo", "")
const result = ctx.mcp.ListPrompts("echo", "")
if (!result || !result.prompts) {
throw new Error("Expected prompts")
@ -349,7 +349,7 @@ func TestMCPGetPrompt(t *testing.T) {
res, err := v8.Call(v8.CallOptions{}, `
function test(ctx) {
// Get test_connection prompt
const result = ctx.MCP.GetPrompt("echo", "test_connection", { detailed: "true" })
const result = ctx.mcp.GetPrompt("echo", "test_connection", { detailed: "true" })
if (!result || !result.messages) {
throw new Error("Expected messages")
@ -392,7 +392,7 @@ func TestMCPListSamples(t *testing.T) {
res, err := v8.Call(v8.CallOptions{}, `
function test(ctx) {
// List samples for ping tool
const result = ctx.MCP.ListSamples("echo", "tool", "ping")
const result = ctx.mcp.ListSamples("echo", "tool", "ping")
if (!result || !result.samples) {
throw new Error("Expected samples")
@ -435,7 +435,7 @@ func TestMCPGetSample(t *testing.T) {
res, err := v8.Call(v8.CallOptions{}, `
function test(ctx) {
// Get first sample for ping tool
const result = ctx.MCP.GetSample("echo", "tool", "ping", 0)
const result = ctx.mcp.GetSample("echo", "tool", "ping", 0)
if (!result) {
throw new Error("Expected sample")
@ -480,10 +480,10 @@ func TestMCPJsApiWithTrace(t *testing.T) {
res, err := v8.Call(v8.CallOptions{}, `
function test(ctx) {
// Get trace (property, not method call)
const trace = ctx.Trace
const trace = ctx.trace
// Call MCP tool - should create trace node
const result = ctx.MCP.CallTool("echo", "ping", { count: 5 })
const result = ctx.mcp.CallTool("echo", "ping", { count: 5 })
// Verify trace and result exist
return {

View file

@ -86,7 +86,7 @@ func TestTraceRelease(t *testing.T) {
res, err := v8.Call(v8.CallOptions{}, `
function test(ctx) {
// Get trace
const trace = ctx.Trace
const trace = ctx.trace
// Verify trace has Release method
if (typeof trace.Release !== 'function') {
@ -149,7 +149,7 @@ func TestContextReleaseWithTrace(t *testing.T) {
res, err := v8.Call(v8.CallOptions{}, `
function test(ctx) {
// Get trace
const trace = ctx.Trace
const trace = ctx.trace
// Use trace
const node = trace.Add({ type: "test" }, { label: "Test Node" })
@ -197,7 +197,7 @@ func TestTryFinallyPattern(t *testing.T) {
res, err := v8.Call(v8.CallOptions{}, `
function test(ctx) {
const trace = ctx.Trace
const trace = ctx.trace
// Try-finally pattern for explicit resource management
try {
@ -247,7 +247,7 @@ func TestNoOpTraceRelease(t *testing.T) {
res, err := v8.Call(v8.CallOptions{}, `
function test(ctx) {
// Get trace (should be no-op)
const trace = ctx.Trace
const trace = ctx.trace
// Verify trace has Release method even when it's no-op
if (typeof trace.Release !== 'function') {
@ -300,7 +300,7 @@ func TestTryFinallyPatternWithError(t *testing.T) {
_, err := v8.Call(v8.CallOptions{}, `
function test(ctx) {
const trace = ctx.Trace
const trace = ctx.trace
// Try-finally pattern ensures cleanup even when error occurs
try {

View file

@ -45,8 +45,8 @@ func TestStressContextCreationAndRelease(t *testing.T) {
_, err := v8.Call(v8.CallOptions{}, `
function test(ctx) {
// Use trace
ctx.Trace.Add({ type: "test" }, { label: "Test" })
ctx.Trace.Info("Processing")
ctx.trace.Add({ type: "test" }, { label: "Test" })
ctx.trace.Info("Processing")
// Explicit release
ctx.Release()
@ -120,7 +120,7 @@ func TestStressTraceOperations(t *testing.T) {
cxt.Stack = stack
_, err := v8.Call(v8.CallOptions{}, fmt.Sprintf(`
function test(ctx) {
const trace = ctx.Trace
const trace = ctx.trace
const nodes = []
// Create multiple nodes
@ -202,16 +202,16 @@ func TestStressMCPOperations(t *testing.T) {
_, err := v8.Call(v8.CallOptions{}, `
function test(ctx) {
// List operations
const tools = ctx.MCP.ListTools("echo", "")
const resources = ctx.MCP.ListResources("echo", "")
const prompts = ctx.MCP.ListPrompts("echo", "")
const tools = ctx.mcp.ListTools("echo", "")
const resources = ctx.mcp.ListResources("echo", "")
const prompts = ctx.mcp.ListPrompts("echo", "")
// Call operations
const result1 = ctx.MCP.CallTool("echo", "ping", { count: 1 })
const result2 = ctx.MCP.CallTool("echo", "status", { verbose: false })
const result1 = ctx.mcp.CallTool("echo", "ping", { count: 1 })
const result2 = ctx.mcp.CallTool("echo", "status", { verbose: false })
// Read operations
const info = ctx.MCP.ReadResource("echo", "echo://info")
const info = ctx.mcp.ReadResource("echo", "echo://info")
return {
tools: tools.tools.length,
@ -283,12 +283,12 @@ func TestStressConcurrentContexts(t *testing.T) {
_, err := v8.Call(v8.CallOptions{}, `
function test(ctx) {
// Use trace
const node = ctx.Trace.Add({ type: "test" }, { label: "Concurrent Test" })
ctx.Trace.Info("Processing concurrent request")
const node = ctx.trace.Add({ type: "test" }, { label: "Concurrent Test" })
ctx.trace.Info("Processing concurrent request")
node.Complete({ result: "success" })
// Use MCP
const tools = ctx.MCP.ListTools("echo", "")
const tools = ctx.mcp.ListTools("echo", "")
// Release resources
ctx.Release()
@ -358,7 +358,7 @@ func TestStressNoOpTracePerformance(t *testing.T) {
for i := 0; i < iterations; i++ {
_, err := v8.Call(v8.CallOptions{}, `
function test(ctx) {
const trace = ctx.Trace // no-op trace
const trace = ctx.trace // no-op trace
// All operations should be no-ops and fast
trace.Info("No-op info")
@ -434,7 +434,7 @@ func TestStressReleasePatterns(t *testing.T) {
_, err := v8.Call(v8.CallOptions{}, `
function test(ctx) {
try {
ctx.Trace.Add({ type: "test" }, { label: "Manual Release" })
ctx.trace.Add({ type: "test" }, { label: "Manual Release" })
return { success: true }
} finally {
ctx.Release() // Manual release
@ -472,7 +472,7 @@ func TestStressReleasePatterns(t *testing.T) {
_, err := v8.Call(v8.CallOptions{}, `
function test(ctx) {
ctx.Trace.Add({ type: "test" }, { label: "GC Release" })
ctx.trace.Add({ type: "test" }, { label: "GC Release" })
return { success: true }
// No manual release - rely on GC
}`, cxt)
@ -514,8 +514,8 @@ func TestStressReleasePatterns(t *testing.T) {
_, err := v8.Call(v8.CallOptions{}, `
function test(ctx) {
try {
ctx.Trace.Add({ type: "test" }, { label: "Separate Release" })
ctx.Trace.Release() // Release trace separately
ctx.trace.Add({ type: "test" }, { label: "Separate Release" })
ctx.trace.Release() // Release trace separately
return { success: true }
} finally {
ctx.Release() // Release context
@ -562,7 +562,7 @@ func TestStressLongRunningTrace(t *testing.T) {
_, err := v8.Call(v8.CallOptions{}, fmt.Sprintf(`
function test(ctx) {
const trace = ctx.Trace
const trace = ctx.trace
const allNodes = []
// Create many nested nodes

View file

@ -417,7 +417,7 @@ func TestJsValueTrace(t *testing.T) {
res, err := v8.Call(v8.CallOptions{}, `
function test(cxt) {
// Get trace from context (property, not method call)
const trace = cxt.Trace
const trace = cxt.trace
// Verify trace object exists
if (!trace) {