feat: validate receive message contract args

This commit is contained in:
zhaoyilun
2026-07-10 01:32:53 +08:00
parent aa636f5a33
commit 95699e05b5
7 changed files with 200 additions and 17 deletions

View File

@@ -2,6 +2,7 @@ package tools
import (
"context"
"fmt"
"strconv"
"strings"
"time"
@@ -18,10 +19,14 @@ type ReceiveMessagesSource interface {
}
type ReceiveMessagesArgs struct {
ConversationID string `json:"conversation_id,omitempty" jsonschema:"exact conversation id filter for local readonly message logs"`
Query string `json:"query,omitempty" jsonschema:"case-insensitive keyword filter over message text, subject, ids, and participants"`
Since string `json:"since,omitempty" jsonschema:"RFC3339 timestamp; return messages at or after this time when packet timestamps are available"`
Limit int `json:"limit,omitempty" jsonschema:"maximum number of messages to return; zero or negative returns all available messages"`
ConversationID string `json:"conversation_id,omitempty" jsonschema:"exact conversation id filter for local readonly message logs"`
Query string `json:"query,omitempty" jsonschema:"case-insensitive keyword filter over message text, subject, ids, and participants"`
Since string `json:"since,omitempty" jsonschema:"RFC3339 timestamp; return messages at or after this time when packet timestamps are available"`
Cursor string `json:"cursor,omitempty" jsonschema:"pagination cursor; currently only empty cursor is supported"`
SourcePreference string `json:"source_preference,omitempty" jsonschema:"source selector; currently supports auto or local_readonly only"`
Preview bool `json:"preview,omitempty" jsonschema:"accepted for contract compatibility; read-only execution remains read mode"`
IncludeAttachmentMetadata *bool `json:"include_attachment_metadata,omitempty" jsonschema:"include inline attachment metadata in receive message results; default true"`
Limit int `json:"limit,omitempty" jsonschema:"maximum number of messages to return; zero or negative returns all available messages"`
}
func RegisterISphereReadTools(server *mcp.Server, source ReceiveMessagesSource) {
@@ -33,6 +38,9 @@ func RegisterISphereReadTools(server *mcp.Server, source ReceiveMessagesSource)
Name: ToolNameReceiveMessages,
Description: "Return iSphere messages from the configured read-only log-backed source.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, input ReceiveMessagesArgs) (*mcp.CallToolResult, map[string]any, error) {
if err := validateReceiveMessagesArgs(input); err != nil {
return nil, nil, err
}
started := time.Now().UTC()
result, err := source.ReceiveMessages(ctx, isphere.ReceiveMessagesQuery{
ConversationID: input.ConversationID,
@@ -43,14 +51,43 @@ func RegisterISphereReadTools(server *mcp.Server, source ReceiveMessagesSource)
if err != nil {
return nil, nil, err
}
return nil, receiveMessagesResultToMap(result, started, time.Now().UTC()), nil
return nil, receiveMessagesResultToMap(result, started, time.Now().UTC(), receiveMessagesMapOptions{
IncludeAttachmentMetadata: includeReceiveMessageAttachmentMetadata(input),
}), nil
})
}
func receiveMessagesResultToMap(result isphere.ReceiveMessagesResult, started time.Time, finished time.Time) map[string]any {
func validateReceiveMessagesArgs(input ReceiveMessagesArgs) error {
sourcePreference := strings.ToLower(strings.TrimSpace(input.SourcePreference))
switch sourcePreference {
case "", "auto", "local_readonly":
default:
return fmt.Errorf("isphere_receive_messages source_preference %q is not available; only auto and local_readonly are supported", input.SourcePreference)
}
if strings.TrimSpace(input.Cursor) != "" {
return fmt.Errorf("isphere_receive_messages cursor pagination is not available yet")
}
return nil
}
func includeReceiveMessageAttachmentMetadata(input ReceiveMessagesArgs) bool {
if input.IncludeAttachmentMetadata == nil {
return true
}
return *input.IncludeAttachmentMetadata
}
type receiveMessagesMapOptions struct {
IncludeAttachmentMetadata bool
}
func receiveMessagesResultToMap(result isphere.ReceiveMessagesResult, started time.Time, finished time.Time, options receiveMessagesMapOptions) map[string]any {
messages := make([]map[string]any, 0, len(result.Messages))
for _, message := range result.Messages {
attachments := receiveMessageAttachments(message)
attachments := []map[string]any{}
if options.IncludeAttachmentMetadata {
attachments = receiveMessageAttachments(message)
}
messages = append(messages, map[string]any{
"id": message.ID,
"message_id": message.ID,

View File

@@ -142,6 +142,75 @@ func TestISphereReceiveMessagesToolReturnsSourceMessages(t *testing.T) {
}
}
func TestISphereReceiveMessagesToolValidatesRemainingContractArgs(t *testing.T) {
fake := &fakeReceiveMessagesSource{
result: isphere.ReceiveMessagesResult{Messages: []isphere.Message{{
ID: "msg-1",
ConversationID: "sender@imopenfire1-lanzhou|receiver@imopenfire1-lanzhou",
ConversationType: "chat",
SenderID: "sender@imopenfire1-lanzhou",
ReceiverID: "receiver@imopenfire1-lanzhou",
Text: "redacted-report.docx",
Timestamp: "1783423807000",
Subject: "FILE_TRANSFER_CANCEL",
}}},
}
session, cleanup := connectToolsTestSession(t, func(server *mcp.Server) {
RegisterISphereReadTools(server, fake)
})
defer cleanup()
callResult, err := session.CallTool(context.Background(), &mcp.CallToolParams{
Name: ToolNameReceiveMessages,
Arguments: map[string]any{
"include_attachment_metadata": false,
"source_preference": "local_readonly",
"preview": true,
"cursor": "",
"limit": 5,
},
})
if err != nil {
t.Fatalf("call with safe contract args: %v", err)
}
if callResult.IsError {
t.Fatalf("call result is error: %+v", callResult)
}
var decoded struct {
Messages []struct {
Attachments []struct {
FileID string `json:"file_id"`
} `json:"attachments"`
} `json:"messages"`
}
payload, err := json.Marshal(callResult.StructuredContent)
if err != nil {
t.Fatalf("marshal structured content: %v", err)
}
if err := json.Unmarshal(payload, &decoded); err != nil {
t.Fatalf("decode structured content %s: %v", payload, err)
}
if len(decoded.Messages) != 1 || len(decoded.Messages[0].Attachments) != 0 {
t.Fatalf("attachments = %+v, want suppressed", decoded.Messages)
}
bridgeResult, err := session.CallTool(context.Background(), &mcp.CallToolParams{
Name: ToolNameReceiveMessages,
Arguments: map[string]any{"source_preference": "bridge", "limit": 5},
})
if err == nil && !bridgeResult.IsError {
t.Fatalf("bridge source_preference was accepted before connector exists")
}
cursorResult, err := session.CallTool(context.Background(), &mcp.CallToolParams{
Name: ToolNameReceiveMessages,
Arguments: map[string]any{"cursor": "next-page", "limit": 5},
})
if err == nil && !cursorResult.IsError {
t.Fatalf("non-empty cursor was accepted before pagination exists")
}
}
type fakeReceiveMessagesSource struct {
queries []isphere.ReceiveMessagesQuery
result isphere.ReceiveMessagesResult