feat: add send file preview tool

This commit is contained in:
zhaoyilun
2026-07-10 21:22:39 +08:00
parent 6781c75f84
commit 1fd10b5df7
9 changed files with 673 additions and 26 deletions

View File

@@ -29,6 +29,7 @@ var expectedTools = []string{
"isphere_search_contacts",
"isphere_search_groups",
"isphere_receive_files",
"isphere_send_file",
"isphere_send_message",
}
@@ -54,6 +55,8 @@ type smokeResult struct {
FixtureDirFileCount int `json:"fixture_dir_file_count"`
SendPreviewToolPresent bool `json:"send_preview_tool_present"`
ProductionSendEnabled bool `json:"production_send_enabled"`
SendFilePreviewToolPresent bool `json:"send_file_preview_tool_present"`
SendFileProductionEnabled bool `json:"send_file_production_enabled"`
LocalLoginRequired bool `json:"local_login_required"`
RealISphereLoginRequired bool `json:"real_isphere_login_required"`
PythonRuntimeRequired bool `json:"python_runtime_required"`
@@ -89,6 +92,17 @@ func run() error {
if err := os.Setenv("ISPHERE_SEND_IDEMPOTENCY_PATH", idempotencyPath); err != nil {
return err
}
sendFileDir := filepath.Join(sendStateDir, "send-file-allowed")
if err := os.MkdirAll(sendFileDir, 0o755); err != nil {
return err
}
sendFilePath := filepath.Join(sendFileDir, "redacted-preview.txt")
if err := os.WriteFile(sendFilePath, []byte("hello"), 0o600); err != nil {
return err
}
if err := os.Setenv("ISPHERE_SEND_FILE_ALLOWED_DIR", sendFileDir); err != nil {
return err
}
session, cleanup, err := newSession(ctx, "isphere-capability-smoke")
if err != nil {
@@ -128,6 +142,10 @@ func run() error {
if err != nil {
return err
}
sendFilePreviewOK, sendFileProductionEnabled, err := verifySendFile(ctx, session, sendFilePath)
if err != nil {
return err
}
fixtureReceiveCount, fixtureContactCount, fixtureGroupCount, fixtureFileCount, err := verifyPacketLogFileFixture(ctx)
if err != nil {
@@ -160,6 +178,8 @@ func run() error {
FixtureDirFileCount: fixtureDirFileCount,
SendPreviewToolPresent: sendPreviewOK,
ProductionSendEnabled: productionSendEnabled,
SendFilePreviewToolPresent: sendFilePreviewOK,
SendFileProductionEnabled: sendFileProductionEnabled,
LocalLoginRequired: false,
RealISphereLoginRequired: false,
PythonRuntimeRequired: false,
@@ -187,6 +207,7 @@ func clearRuntimeEnv() {
"ISPHERE_MSGLIB_SQLITE_DLL",
"ISPHERE_MSGLIB_DB",
"ISPHERE_MSGLIB_PASSWORD",
"ISPHERE_SEND_FILE_ALLOWED_DIR",
} {
_ = os.Unsetenv(key)
}
@@ -416,6 +437,55 @@ func verifySendMessage(ctx context.Context, session *mcp.ClientSession) (bool, b
return true, false, nil
}
func verifySendFile(ctx context.Context, session *mcp.ClientSession, filePath string) (bool, bool, error) {
fileHash, err := sha256FileHex(filePath)
if err != nil {
return false, false, err
}
preview, err := callToolObject(ctx, session, "isphere_send_file", map[string]any{
"target_type": "direct",
"target_id": "sender@imopenfire1-lanzhou",
"file_path": filePath,
"file_sha256": fileHash,
"idempotency_key": "capability-file-preview-idempotency-key",
"execution_mode": "preview",
"preview": true,
})
if err != nil {
return false, false, err
}
if preview["ok"] != true || preview["send_status"] != "planned" || preview["file_sha256"] != fileHash || preview["file_size_bytes"] != float64(5) {
return false, false, fmt.Errorf("unexpected send-file preview payload: %#v", preview)
}
sideEffects, ok := preview["side_effect_flags"].(map[string]any)
if !ok || sideEffects["sent_file"] != false || sideEffects["uploaded_file"] != false || sideEffects["clicked_ui"] != false {
return false, false, fmt.Errorf("send-file preview side effects mismatch: %#v", preview["side_effect_flags"])
}
if preview["production_send_enabled"] != false || preview["real_send_attempted"] != false {
return false, false, fmt.Errorf("send-file preview should not enable or attempt send: %#v", preview)
}
production, err := callToolObject(ctx, session, "isphere_send_file", map[string]any{
"target_type": "direct",
"target_id": "sender@imopenfire1-lanzhou",
"file_path": filePath,
"file_sha256": fileHash,
"idempotency_key": "capability-file-production-idempotency-key",
"execution_mode": "production",
})
if err != nil {
return false, false, err
}
if production["ok"] != false || production["send_status"] != "blocked" || production["production_send_enabled"] != false || production["real_send_attempted"] != false {
return false, false, fmt.Errorf("production send-file was not blocked: %#v", production)
}
productionSideEffects, ok := production["side_effect_flags"].(map[string]any)
if !ok || productionSideEffects["sent_file"] != false || productionSideEffects["uploaded_file"] != false || productionSideEffects["captured_network"] != false {
return false, false, fmt.Errorf("production send-file side effects mismatch: %#v", production["side_effect_flags"])
}
return true, false, nil
}
func verifyPacketLogFileFixture(ctx context.Context) (int, int, int, int, error) {
plaintext := fixturePacketLogPlaintext("msg-fixture-1", "redacted-report.docx")
line, err := encryptPacketLogLine(plaintext)
@@ -568,6 +638,14 @@ func sha256Hex(value string) string {
return hex.EncodeToString(sum[:])
}
func sha256FileHex(path string) (string, error) {
payload, err := os.ReadFile(path)
if err != nil {
return "", err
}
return sha256Hex(string(payload)), nil
}
func replaceEnv(key string, value string) func() {
oldValue, hadOldValue := os.LookupEnv(key)
if value == "" {

View File

@@ -14,7 +14,7 @@ Remote base before local roadmap commits: `b2d839e Merge branch 'codex/n15-repor
## Current completed state
- Go MCP foundation exists: `cmd/isphere-mcp`, `internal/mcpserver`, `internal/helperclient`, and `internal/tools` build a stdio MCP server.
- The current MCP surface exposes nine tools: four WinHelper observation tools, four read-oriented business tools, and one send-message preview-only tool:
- The current MCP surface exposes ten tools: four WinHelper observation tools, four read-oriented business tools, one send-message preview-only tool, and one send-file preview-only tool:
- `win_helper_version`
- `win_helper_self_check`
- `win_helper_scan_windows`
@@ -24,8 +24,9 @@ Remote base before local roadmap commits: `b2d839e Merge branch 'codex/n15-repor
- `isphere_search_groups`
- `isphere_receive_files`
- `isphere_send_message` preview/dry-run only; production is blocked
- `isphere_send_file` preview/dry-run only; production file upload is blocked
- C# `ISphereWinHelper` exists under `native/ISphereWinHelper` and uses the `isphere.helper.v1` stdin/stdout JSON contract. Helper `0.4.0` adds read-only `probe_send_entrypoints` and `probe_send_uia_controls` for R6a/C31 send connector preflight.
- `scripts/verify-win-helper.ps1` and `scripts/verify-go-mcp.ps1` provide repeatable local checks for the helper, nine-tool MCP surface, default empty-source receive/contact/group/file calls, send-message preview/production-blocked behavior, synthetic configured-file receive/contact/group/file smoke, and synthetic configured-directory receive/contact/group/file smoke.
- `scripts/verify-win-helper.ps1` and `scripts/verify-go-mcp.ps1` provide repeatable local checks for the helper, ten-tool MCP surface, default empty-source receive/contact/group/file calls, send-message preview/production-blocked behavior, send-file preview/production-blocked behavior, synthetic configured-file receive/contact/group/file smoke, and synthetic configured-directory receive/contact/group/file smoke.
- `isphere_receive_messages` now returns the contract-facing `ok`, `conversation`, `messages`, `next_cursor`, and `audit` envelope while retaining legacy parser-native message fields for compatibility.
- `isphere_receive_messages` accepts the read-contract argument set for the current local-readonly path: `conversation_id`, `query`, `since`, `limit`, `include_attachment_metadata`, `source_preference`, `preview`, and empty `cursor`.
- `isphere_search_contacts` and `isphere_search_groups` accept and validate the safe search-contract args for the current local-readonly path and can optionally enrich results from the env-configured C29 `MsgLib.db` display-entity reader; default behavior remains log/JID-backed when MsgLib env vars are absent.
@@ -37,7 +38,7 @@ Remote base before local roadmap commits: `b2d839e Merge branch 'codex/n15-repor
## What cannot be claimed externally
- The project has not yet implemented production message sending, file download, or file sending; `isphere_receive_messages`, `isphere_search_contacts`, `isphere_search_groups`, and `isphere_receive_files` list mode have operator-local encrypted log-file/log-directory support but not a production ingestion path.
- The project has not yet implemented production message sending, file download, or production file sending; `isphere_receive_messages`, `isphere_search_contacts`, `isphere_search_groups`, and `isphere_receive_files` list mode have operator-local encrypted log-file/log-directory support but not a production ingestion path.
- The project has not completed production iSphere integration.
- The project has not proven a stable real message source for the full business workflow beyond decrypted PacketReader log evidence and synthetic/redacted tests.
- The project has not implemented real message sending or real file upload. R6b adds preview/dry-run only; it does not prove send invocation, success/ack, or idempotent production behavior.
@@ -49,7 +50,7 @@ Remote base before local roadmap commits: `b2d839e Merge branch 'codex/n15-repor
- The repository has a Go MCP + C# WinHelper foundation for controlled Windows-side read-only observation.
- The helper protocol boundary is explicit and keeps Windows/UIA work separate from the Go MCP service layer.
- The current code can support future MCP business tools by routing low-level Windows/UIA fallback work through a bounded helper layer.
- The project has repeatable verification scripts for the helper/MCP foundation and the current nine-tool surface.
- The project has repeatable verification scripts for the helper/MCP foundation and the current ten-tool surface.
- The project now has a corrected business contract and plan for core MCP communication tools, plus registered receive/contact/group/file-list read tools that can use `ISPHERE_PACKET_LOG_FILE` for one operator-local encrypted PacketReader log-line file or `ISPHERE_PACKET_LOG_DIR` for an operator-local directory of encrypted `.log`/`.txt` PacketReader files.
## N13/N14/N15 positioning
@@ -58,7 +59,7 @@ N13/N14/N15 are pre-business validation results. They can help identify UI eleme
## Current loop
Current loop: `R6l send-message production path gate closure complete; next R7 send-file preview tool`.
Current loop: `R7 send-file preview tool complete`; next R8 send-file idempotency and audit hardening.
Active continuous execution plan: `docs/superpowers/plans/2026-07-10-r6f-r14-continuous-execution-plan.md`.
@@ -239,8 +240,8 @@ Continuous execution plan R6f-R14 is approved and execution has started:
- Plan file: `docs/superpowers/plans/2026-07-10-r6f-r14-continuous-execution-plan.md`.
- Scope: 15 ordered rounds covering send-message connector/gate hardening, send-file preview/idempotency/package, receive-file download preview, receive-message reconciliation, end-to-end business smoke, and release-candidate report.
- Execution rule after approval: one round at a time, status-card update, verification, commit, push, then continue automatically until an evidence-only blocker requires user action.
- Last completed round: R6l send-message production path gate closure.
- Next active round: R7 send-file preview tool.
- Last completed round: R7 send-file preview tool.
- Next active round: R8 send-file idempotency and audit hardening.
R6g send audit and idempotency replay diagnostics is complete:
@@ -295,3 +296,12 @@ R6l send-message production path gate closure is complete:
- Added an explicit skipped gated-production test with reason `strict v2 send evidence not present in this repository state`.
- Standard verification still reports 9 tools and `production_send_enabled=false`.
- Next node: R7 send-file preview tool.
R7 send-file preview tool is complete:
- Added `isphere_send_file` as the tenth MCP tool.
- Preview validates target, idempotency key, `ISPHERE_SEND_FILE_ALLOWED_DIR`, file existence, file SHA256, and file size.
- Preview returns `send_status="planned"`, `real_send_attempted=false`, `production_send_enabled=false`, `file_sha256`, `file_size_bytes`, and all upload/send side-effect flags false.
- `execution_mode="production"` returns structured blocked metadata; no upload, click, type, hook, network capture, or client mutation is introduced.
- Verification passed: focused send-file tests, 10-tool MCP registration test, `go test ./...`, `go build ./cmd/isphere-mcp`, `scripts\verify-go-mcp.ps1`, and `go run ./cmd/isphere-capability-smoke`.
- Next node: R8 send-file idempotency and audit hardening.

View File

@@ -2,7 +2,7 @@
This runbook is for the first Go MCP phase of `isphere-ai-bridge`. It lets an operator build and verify the Windows helper and the Go MCP server without reading the source code.
Current scope: expose four WinHelper observation operations, four business read tools, and one preview-only send-message tool through Go MCP. Read tools are `isphere_receive_messages`, `isphere_search_contacts`, `isphere_search_groups`, and `isphere_receive_files` list mode. The send tool is `isphere_send_message` preview/dry-run only; production send is blocked. Read tools use an empty default message source unless `ISPHERE_PACKET_LOG_FILE` points to an operator-local encrypted PacketReader log-line file or `ISPHERE_PACKET_LOG_DIR` points to an operator-local directory of encrypted PacketReader `.log`/`.txt` files. Contact/group display names can also be optionally enriched from an operator-local copied `MsgLib.db` through the bounded read-only `MsgLibReadSidecar`; receive messages can use copied DB rows only when the caller explicitly passes `source_preference="msglib_readonly"`.
Current scope: expose four WinHelper observation operations, four business read tools, and two preview-only send tools through Go MCP. Read tools are `isphere_receive_messages`, `isphere_search_contacts`, `isphere_search_groups`, and `isphere_receive_files` list mode. Send tools are `isphere_send_message` and `isphere_send_file` preview/dry-run only; production send/file upload is blocked. Read tools use an empty default message source unless `ISPHERE_PACKET_LOG_FILE` points to an operator-local encrypted PacketReader log-line file or `ISPHERE_PACKET_LOG_DIR` points to an operator-local directory of encrypted PacketReader `.log`/`.txt` files. Contact/group display names can also be optionally enriched from an operator-local copied `MsgLib.db` through the bounded read-only `MsgLibReadSidecar`; receive messages can use copied DB rows only when the caller explicitly passes `source_preference="msglib_readonly"`.
## 1. Prerequisites
@@ -90,7 +90,7 @@ The verification confirms:
- C# helper can be built.
- Go MCP binary can be built.
- MCP initialize/list/call flow works through the SDK harness.
- Exactly nine tools are exposed: four WinHelper observation tools plus `isphere_receive_messages`, `isphere_search_contacts`, `isphere_search_groups`, `isphere_receive_files`, and preview-only `isphere_send_message`.
- Exactly ten tools are exposed: four WinHelper observation tools plus `isphere_receive_messages`, `isphere_search_contacts`, `isphere_search_groups`, `isphere_receive_files`, preview-only `isphere_send_message`, and preview-only `isphere_send_file`.
- `win_helper_version` returns `ISphereWinHelper`.
- `isphere_receive_messages` is callable and returns an empty `messages` array from the default empty source.
- `isphere_receive_messages` returns the contract-facing `ok`, `conversation`, `messages`, `next_cursor`, and `audit` envelope, while preserving legacy message aliases such as `id`, `text`, and `timestamp`.
@@ -100,11 +100,12 @@ The verification confirms:
- `isphere_search_groups` is callable and returns JID-derived group candidates from the configured synthetic groupchat fixture; exact ID/display-name matches rank before prefix/substring matches and case-insensitive duplicates are collapsed.
- `isphere_receive_files` is callable in list mode and returns one file metadata candidate from the configured synthetic file-transfer fixture.
- `isphere_send_message` is callable in preview mode and returns `send_status="planned"` without raw content in the response; the default runtime still returns `execution_mode="production"` as `send_status="blocked"` and `production_send_enabled=false`.
- `isphere_send_file` is callable in preview mode when `ISPHERE_SEND_FILE_ALLOWED_DIR` points to the allowed local directory; it returns file SHA256/size metadata only, does not return file content, and keeps production upload blocked with `production_send_enabled=false`.
- `isphere_send_message` also exposes sandbox-only connector metadata and idempotency state: duplicate reuse of the same key for the same target/content is detectable, while conflicting reuse of the same key for different content/target is blocked.
- R6f adds a test-only fake/sandbox connector contract for accepted/failed connector outcomes. This is an injected unit-test boundary only; the production MCP server still registers no real connector and performs no real send.
- Verification uses synthetic/local helper checks and does not load raw N12-pre evidence.
- The deterministic verification path clears MsgLib env variables, so it proves the default no-MsgLib behavior remains stable.
- File download/cache mapping, send-file, and production send remain later-stage work.
- File download/cache mapping, production message send, and production file upload remain later-stage work.
## 6. Configure optional message source
@@ -240,7 +241,7 @@ E:\coding\codex\isphere-ai-bridge\isphere-mcp.exe
## 9. Allowed tools
These nine tools are currently allowed:
These ten tools are currently allowed:
| Tool | Source/op | Purpose |
| --- | --- | --- |
@@ -253,6 +254,7 @@ These nine tools are currently allowed:
| `isphere_search_groups` | log-backed groupchat JIDs plus optional MsgLib display enrichment | Search group candidates extracted from groupchat/conference/MUC bare JIDs in the configured message source, with deterministic exact-match-first ranking, case-insensitive de-duplication, and preserved `source`/`raw_ref`. |
| `isphere_receive_files` | log-backed file-transfer messages | List file metadata candidates extracted from file-transfer message bodies. Download/cache mapping is not implemented yet. |
| `isphere_send_message` | B-route preview/dry-run contract | Plan a text-message send with target/content hash/idempotency/audit metadata. Production send is blocked. |
| `isphere_send_file` | file-send preview/dry-run contract | Plan a file send with target/file SHA256/size/idempotency metadata. Production upload is blocked. |
Allowed parameters:
@@ -265,6 +267,7 @@ Allowed parameters:
- `isphere_search_groups`: `query`, `cursor`, `source_preference`, `include_archived`, `limit` only. `source_preference` currently supports empty/`auto`/`local_readonly`; `cursor` must be empty until pagination is implemented.
- `isphere_receive_files`: `conversation_id`, `message_id`, `file_id`, `name_contains`, `mode`, `output_dir`, `cursor`, `source_preference`, `preview`, `limit` only. C22 supports `mode` empty or `list`; `source_preference` currently supports empty/`auto`/`local_readonly`; `cursor` and `output_dir` must be empty in current list-only mode; download is deferred.
- `isphere_send_message`: `target_type`, `target_id`, `content_text`, `content_sha256`, `idempotency_key`, `execution_mode` only. R6b supports `execution_mode` empty/`preview`/`dry_run` as planned preview. The default runtime returns `execution_mode="production"` as blocked until sandbox-send evidence passes. R6f adds a Go `SendMessageConnector` interface for fake/sandbox tests so accepted, failed, duplicate, and conflict paths can be validated without login. The response and audit store `content_sha256` and `idempotency_key_sha256`, not raw message body or raw idempotency key.
- `isphere_send_file`: `target_type`, `target_id`, `file_path`, `file_sha256`, `idempotency_key`, `execution_mode`, `preview` only. `file_path` must stay inside `ISPHERE_SEND_FILE_ALLOWED_DIR`; preview computes/validates `file_sha256` and `file_size_bytes`, returns `real_send_attempted=false`, and does not upload or return file content. The default runtime returns `execution_mode="production"` as blocked.
Optional send audit/idempotency paths:
@@ -275,6 +278,14 @@ $env:ISPHERE_SEND_IDEMPOTENCY_PATH = "E:\coding\codex\isphere-ai-bridge\runs\sen
If `ISPHERE_SEND_IDEMPOTENCY_PATH` is set, the send preview path records hashed idempotency state. Reusing the same idempotency key for the same target/content sets `duplicate_detected=true`; reusing it for different content or target returns blocked metadata with `conflict_detected=true`. Raw message body and raw idempotency key are not stored in the JSONL state.
Send-file preview requires an explicit allowed directory. Put only the files you want the digital employee to plan against inside that directory:
```powershell
$env:ISPHERE_SEND_FILE_ALLOWED_DIR = "E:\coding\codex\isphere-ai-bridge\runs\send-file-preview"
```
`isphere_send_file` rejects `file_path` values outside that directory. It computes file SHA256 and size, but does not upload, click, type, or return file content.
R6g adds a local diagnostic for replaying the redacted audit/idempotency files without opening iSphere:
```powershell
@@ -298,7 +309,7 @@ R6l closes the current send-message production path after R6k: because `strict_v
## 10. Current tool surface and next-stage route
The current runbook verifies nine tools:
The current runbook verifies ten tools:
- `win_helper_version`
- `win_helper_self_check`
@@ -309,10 +320,11 @@ The current runbook verifies nine tools:
- `isphere_search_groups`
- `isphere_receive_files`
- `isphere_send_message`
- `isphere_send_file`
The current log-backed business read tools have parser/source/tool registration and an empty default server source. Raw N12-pre evidence remains under ignored `runs/` paths and is not committed. The current command entry point can read an operator-local encrypted PacketReader log-line file via `ISPHERE_PACKET_LOG_FILE` or a directory of `.log`/`.txt` files via `ISPHERE_PACKET_LOG_DIR`; this is still not a production ingestion claim because raw evidence remains local and uncommitted. `isphere_receive_messages` now exposes contract-facing fields for digital-employee consumption while preserving older aliases for compatibility, supports `conversation_id`, keyword `query`, and RFC3339 `since` filtering, and validates the remaining safe contract args without pretending unsupported connectors/pagination exist. Contact and group search also accept the safe local-readonly contract args, rank exact matches before prefix/substring matches, collapse case-insensitive duplicates across log-derived candidates and optional `MsgLibReadSidecar` display metadata, and preserve `source`/`raw_ref`; receive-message `sender_name` and `conversation.display_name` can use that same optional metadata when MsgLib env is configured. `isphere_receive_files` supports list mode with safe contract arg validation; download/cache mapping remains deferred. `isphere_send_message` supports preview/dry-run metadata, sandbox-only connector-shell metadata, duplicate/conflict idempotency detection, redacted audit, and a test-only `SendMessageConnector` contract for fake accepted/failed outcomes; the default MCP server still has no real connector and production send remains blocked until dynamic observation, a full send evidence gate, and a controlled sandbox connector pass prove success/ack behavior.
The current log-backed business read tools have parser/source/tool registration and an empty default server source. Raw N12-pre evidence remains under ignored `runs/` paths and is not committed. The current command entry point can read an operator-local encrypted PacketReader log-line file via `ISPHERE_PACKET_LOG_FILE` or a directory of `.log`/`.txt` files via `ISPHERE_PACKET_LOG_DIR`; this is still not a production ingestion claim because raw evidence remains local and uncommitted. `isphere_receive_messages` now exposes contract-facing fields for digital-employee consumption while preserving older aliases for compatibility, supports `conversation_id`, keyword `query`, and RFC3339 `since` filtering, and validates the remaining safe contract args without pretending unsupported connectors/pagination exist. Contact and group search also accept the safe local-readonly contract args, rank exact matches before prefix/substring matches, collapse case-insensitive duplicates across log-derived candidates and optional `MsgLibReadSidecar` display metadata, and preserve `source`/`raw_ref`; receive-message `sender_name` and `conversation.display_name` can use that same optional metadata when MsgLib env is configured. `isphere_receive_files` supports list mode with safe contract arg validation; download/cache mapping remains deferred. `isphere_send_message` supports preview/dry-run metadata, sandbox-only connector-shell metadata, duplicate/conflict idempotency detection, redacted audit, and a test-only `SendMessageConnector` contract for fake accepted/failed outcomes; `isphere_send_file` now exposes preview/dry-run file SHA256/size planning behind `ISPHERE_SEND_FILE_ALLOWED_DIR` with all upload/send side-effect flags false. The default MCP server still has no real message/file connector and production send/file upload remains blocked until dynamic observation, full evidence gates, and controlled sandbox connector passes prove success/ack behavior.
Core business tools for contacts, groups, messages, and files are defined in `docs/mcp-core-tools-contract.md`. Send-message preview metadata and audit records are now in place; production send still waits for the later online sandbox-send gate.
Core business tools for contacts, groups, messages, and files are defined in `docs/mcp-core-tools-contract.md`. Send-message preview metadata and audit records are now in place; send-file preview metadata is in place with allowed-directory validation. Production message send and file upload still wait for later online sandbox evidence gates.
## 11. Real-login UIA capture procedure
@@ -495,16 +507,18 @@ Expected final JSON includes:
```json
{
"ok": true,
"tool_count": 9,
"tool_count": 10,
"helper_name": "ISphereWinHelper",
"send_preview_tool_present": true,
"production_send_enabled": false,
"send_file_preview_tool_present": true,
"send_file_production_enabled": false,
"local_login_required": false,
"no_real_send": true
}
```
This package includes `isphere-capability-smoke.exe` and `runs\win-helper\ISphereWinHelper.exe`. It verifies the nine-tool MCP surface, fixture-backed receive/search/file-list behavior, send preview, and the production-send block. It does not log in, click, type, upload, hook, inject, or send.
This package includes `isphere-capability-smoke.exe` and `runs\win-helper\ISphereWinHelper.exe`. It verifies the ten-tool MCP surface, fixture-backed receive/search/file-list behavior, send preview, send-file preview, and the production-send/file-upload blocks. It does not log in, click, type, upload, hook, inject, or send.
## 16. Troubleshooting

View File

@@ -535,23 +535,23 @@ git push gitea main
- Env: `ISPHERE_SEND_FILE_ALLOWED_DIR` required for previewing real local file paths.
- Response fields: `ok`, `send_status`, `file_sha256`, `file_size_bytes`, `target_ref`, `production_send_enabled`, `side_effect_flags`.
- [ ] **Step 1: Write file-preview test**
- [x] **Step 1: Write file-preview test**
Add `TestISphereSendFilePreviewComputesHashAndSize`, creating a temp allowed directory and `hello.txt`, then asserting preview returns `ok=true`, `send_status="planned"`, `file_size_bytes=5`, and `real_send_attempted=false`.
- [ ] **Step 2: Write path rejection test**
- [x] **Step 2: Write path rejection test**
Add `TestISphereSendFileRejectsPathOutsideAllowedDir` asserting paths outside `ISPHERE_SEND_FILE_ALLOWED_DIR` return `ok=false` and `send_status="blocked"`.
- [ ] **Step 3: Implement tool and registration**
- [x] **Step 3: Implement tool and registration**
Register the tenth MCP tool. Production execution returns blocked with `production_send_enabled=false`.
- [ ] **Step 4: Update smoke scripts**
- [x] **Step 4: Update smoke scripts**
`verify-go-mcp.ps1` and `isphere-capability-smoke` must assert tool count includes `isphere_send_file`, preview works with a temp fixture file, and production remains blocked.
- [ ] **Step 5: Verify and commit**
- [x] **Step 5: Verify and commit**
```powershell
git diff --check
@@ -566,6 +566,15 @@ git push gitea main
**Acceptance gate:** 数字员工能看到“发文件”工具,但默认路径只做 preview不上传。
**R7 Result:**
- Added `internal/tools/isphere_send_file.go` and `internal/tools/isphere_send_file_test.go`.
- Registered `isphere_send_file` as the tenth MCP tool.
- Preview requires `ISPHERE_SEND_FILE_ALLOWED_DIR`, validates target/idempotency/file existence/path boundary/SHA256/size, and returns `send_status="planned"` with `real_send_attempted=false`.
- Production `execution_mode="production"` remains structured blocked with `production_send_enabled=false` and all send/upload/UI/network side-effect flags false.
- Updated `scripts/verify-go-mcp.ps1` and `cmd/isphere-capability-smoke` to assert 10 tools, send-file preview readiness, and send-file production disabled.
- Verification passed: `git diff --check`, focused send-file tests, 10-tool registration test, `go test ./...`, `go build ./cmd/isphere-mcp`, `scripts\verify-go-mcp.ps1`, and `go run ./cmd/isphere-capability-smoke`.
---
### R8: Send-file idempotency and audit hardening

View File

@@ -112,5 +112,6 @@ func NewServerWithSourcesAndMsgLibReceive(source tools.ReceiveMessagesSource, di
tools.RegisterISphereGroupToolsWithDisplayEntities(server, source, displaySource)
tools.RegisterISphereFileTools(server, source)
tools.RegisterISphereSendMessageTool(server, nil)
tools.RegisterISphereSendFileTool(server)
return server
}

View File

@@ -25,7 +25,7 @@ func TestNewServerConstructsMCPServer(t *testing.T) {
}
}
func TestNewServerRegistersNineToolsWithoutCallingHelper(t *testing.T) {
func TestNewServerRegistersTenToolsWithoutCallingHelper(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
serverTransport, clientTransport := mcp.NewInMemoryTransports()
server := NewServer()
@@ -60,7 +60,7 @@ func TestNewServerRegistersNineToolsWithoutCallingHelper(t *testing.T) {
gotNames = append(gotNames, tool.Name)
}
sort.Strings(gotNames)
wantNames := []string{"isphere_receive_files", "isphere_receive_messages", "isphere_search_contacts", "isphere_search_groups", "isphere_send_message", "win_helper_dump_uia", "win_helper_scan_windows", "win_helper_self_check", "win_helper_version"}
wantNames := []string{"isphere_receive_files", "isphere_receive_messages", "isphere_search_contacts", "isphere_search_groups", "isphere_send_file", "isphere_send_message", "win_helper_dump_uia", "win_helper_scan_windows", "win_helper_self_check", "win_helper_version"}
if !reflect.DeepEqual(gotNames, wantNames) {
t.Fatalf("server tool names = %#v, want %#v", gotNames, wantNames)
}

View File

@@ -0,0 +1,257 @@
package tools
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"time"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
const (
ToolNameSendFile = "isphere_send_file"
EnvSendFileAllowedDir = "ISPHERE_SEND_FILE_ALLOWED_DIR"
sendFileConnector = "implatform-file-transfer"
sendFileConnectorMode = "preview-only"
sendFilePreviewStage = "preview"
sendFileBlockedStage = "blocked"
sendFileProductionMode = "production"
)
type SendFileArgs struct {
TargetType string `json:"target_type" jsonschema:"target type; direct/contact or group/groupchat"`
TargetID string `json:"target_id" jsonschema:"contact or group id returned by iSphere search tools"`
FilePath string `json:"file_path" jsonschema:"local file path under ISPHERE_SEND_FILE_ALLOWED_DIR to hash and preview"`
FileSHA256 string `json:"file_sha256,omitempty" jsonschema:"optional lowercase SHA256 hex of file contents; checked when supplied"`
IdempotencyKey string `json:"idempotency_key" jsonschema:"required idempotency key; returned only as SHA256"`
ExecutionMode string `json:"execution_mode,omitempty" jsonschema:"preview/dry_run or production; production is blocked until file-send evidence passes"`
Preview bool `json:"preview,omitempty" jsonschema:"accepted for contract compatibility; current implementation is preview-only"`
}
type normalizedSendFileArgs struct {
TargetType string
TargetID string
TargetRef string
FileName string
FileSHA256 string
FileSizeBytes int64
IdempotencyKeySHA256 string
ExecutionMode string
}
func RegisterISphereSendFileTool(server *mcp.Server) {
mcp.AddTool[SendFileArgs, map[string]any](server, &mcp.Tool{
Name: ToolNameSendFile,
Description: "Preview iSphere file sends with target/file hash/idempotency metadata; production file upload is blocked until sandbox evidence passes.",
}, func(ctx context.Context, _ *mcp.CallToolRequest, input SendFileArgs) (*mcp.CallToolResult, map[string]any, error) {
_ = ctx
started := time.Now().UTC()
normalized, blockedReason, err := normalizeSendFileArgs(input)
if err != nil {
return nil, nil, err
}
if blockedReason != "" {
return nil, sendFileResponse(normalized, started, time.Now().UTC(), false, blockedReason), nil
}
if normalized.ExecutionMode == sendFileProductionMode {
return nil, sendFileResponse(normalized, started, time.Now().UTC(), false, "production file upload is blocked until send-file sandbox evidence passes"), nil
}
return nil, sendFileResponse(normalized, started, time.Now().UTC(), true, ""), nil
})
}
func normalizeSendFileArgs(input SendFileArgs) (normalizedSendFileArgs, string, error) {
targetType, targetRefPrefix, err := normalizeSendFileTargetType(input.TargetType)
if err != nil {
return normalizedSendFileArgs{}, "", err
}
targetID := strings.TrimSpace(input.TargetID)
if targetID == "" {
return normalizedSendFileArgs{}, "", fmt.Errorf("%s target_id is required", ToolNameSendFile)
}
idempotencyKey := strings.TrimSpace(input.IdempotencyKey)
if idempotencyKey == "" {
return normalizedSendFileArgs{}, "", fmt.Errorf("%s idempotency_key is required", ToolNameSendFile)
}
mode, err := normalizeSendFileExecutionMode(input.ExecutionMode)
if err != nil {
return normalizedSendFileArgs{}, "", err
}
normalized := normalizedSendFileArgs{
TargetType: targetType,
TargetID: targetID,
TargetRef: targetRefPrefix + ":" + targetID,
FileName: filepath.Base(strings.TrimSpace(input.FilePath)),
IdempotencyKeySHA256: sha256Hex(idempotencyKey),
ExecutionMode: mode,
}
fileSHA256, fileSize, blockedReason, err := inspectSendFilePath(input.FilePath, input.FileSHA256)
if err != nil {
return normalizedSendFileArgs{}, "", err
}
normalized.FileSHA256 = fileSHA256
normalized.FileSizeBytes = fileSize
return normalized, blockedReason, nil
}
func normalizeSendFileTargetType(value string) (string, string, error) {
switch strings.ToLower(strings.TrimSpace(value)) {
case "direct", "contact":
return "direct", "contact", nil
case "group", "groupchat":
return "group", "group", nil
default:
return "", "", fmt.Errorf("%s target_type %q is not available; use direct or group", ToolNameSendFile, value)
}
}
func normalizeSendFileExecutionMode(value string) (string, error) {
switch strings.ToLower(strings.TrimSpace(value)) {
case "", "preview", "dry_run", "dry-run":
return "preview", nil
case sendFileProductionMode:
return sendFileProductionMode, nil
default:
return "", fmt.Errorf("%s execution_mode %q is not available; use preview or production", ToolNameSendFile, value)
}
}
func inspectSendFilePath(filePath string, providedSHA256 string) (string, int64, string, error) {
trimmedPath := strings.TrimSpace(filePath)
if trimmedPath == "" {
return "", 0, "", fmt.Errorf("%s file_path is required", ToolNameSendFile)
}
allowedDir := strings.TrimSpace(os.Getenv(EnvSendFileAllowedDir))
if allowedDir == "" {
return "", 0, fmt.Sprintf("%s is required before previewing local file paths", EnvSendFileAllowedDir), nil
}
allowedAbs, err := filepath.Abs(allowedDir)
if err != nil {
return "", 0, "", fmt.Errorf("%s allowed dir: %w", ToolNameSendFile, err)
}
fileAbs, err := filepath.Abs(trimmedPath)
if err != nil {
return "", 0, "", fmt.Errorf("%s file_path: %w", ToolNameSendFile, err)
}
if !sendFilePathInsideDir(fileAbs, allowedAbs) {
return "", 0, fmt.Sprintf("file_path must stay inside %s", EnvSendFileAllowedDir), nil
}
info, err := os.Stat(fileAbs)
if err != nil {
if os.IsNotExist(err) {
return "", 0, "file_path does not exist under allowed directory", nil
}
return "", 0, "", fmt.Errorf("%s stat file_path: %w", ToolNameSendFile, err)
}
if info.IsDir() {
return "", 0, "file_path points to a directory; choose one file", nil
}
fileHash, err := sha256FileHex(fileAbs)
if err != nil {
return "", 0, "", fmt.Errorf("%s hash file_path: %w", ToolNameSendFile, err)
}
normalizedProvided := strings.ToLower(strings.TrimSpace(providedSHA256))
if normalizedProvided != "" {
if len(normalizedProvided) != 64 || !isLowerHex(normalizedProvided) {
return "", 0, "", fmt.Errorf("%s file_sha256 must be a lowercase SHA256 hex value", ToolNameSendFile)
}
if normalizedProvided != fileHash {
return "", 0, "", fmt.Errorf("%s file_sha256 does not match file contents", ToolNameSendFile)
}
}
return fileHash, info.Size(), "", nil
}
func sendFilePathInsideDir(fileAbs string, allowedAbs string) bool {
rel, err := filepath.Rel(filepath.Clean(allowedAbs), filepath.Clean(fileAbs))
if err != nil {
return false
}
if rel == "." {
return true
}
return rel != ".." && !strings.HasPrefix(rel, ".."+string(os.PathSeparator)) && !filepath.IsAbs(rel)
}
func sha256FileHex(path string) (string, error) {
file, err := os.Open(path)
if err != nil {
return "", err
}
defer file.Close()
hash := sha256.New()
if _, err := io.Copy(hash, file); err != nil {
return "", err
}
return hex.EncodeToString(hash.Sum(nil)), nil
}
func sendFileResponse(input normalizedSendFileArgs, started time.Time, finished time.Time, planned bool, blockedReason string) map[string]any {
sideEffects := sendMessageNoSideEffects()
status := "planned"
stage := sendFilePreviewStage
ok := true
blocked := any(nil)
if !planned {
status = "blocked"
stage = sendFileBlockedStage
ok = false
blocked = blockedReason
}
auditRef := "send-file:" + shortHash(input.FileSHA256) + ":" + shortHash(input.IdempotencyKeySHA256)
return map[string]any{
"ok": ok,
"send_status": status,
"blocked_reason": blocked,
"execution_mode": input.ExecutionMode,
"connector": sendFileConnector,
"connector_mode": sendFileConnectorMode,
"connector_stage": stage,
"production_send_enabled": false,
"real_send_attempted": false,
"target_ref": input.TargetRef,
"file_sha256": input.FileSHA256,
"file_size_bytes": input.FileSizeBytes,
"target": map[string]any{
"target_type": input.TargetType,
"target_id": input.TargetID,
"target_ref": input.TargetRef,
},
"file": map[string]any{
"file_name": input.FileName,
"file_sha256": input.FileSHA256,
"file_size_bytes": input.FileSizeBytes,
"allowed_dir_enforced": true,
"file_content_returned": false,
},
"idempotency": map[string]any{
"idempotency_key_sha256": input.IdempotencyKeySHA256,
},
"side_effect_flags": sideEffects,
"side_effects": sideEffects,
"audit": map[string]any{
"tool": ToolNameSendFile,
"source": sendFileConnector,
"execution_mode": input.ExecutionMode,
"connector": sendFileConnector,
"connector_mode": sendFileConnectorMode,
"connector_stage": stage,
"file_sha256": input.FileSHA256,
"file_size_bytes": input.FileSizeBytes,
"target_ref": input.TargetRef,
"audit_ref": auditRef,
"started_at": started.Format(time.RFC3339Nano),
"finished_at": finished.Format(time.RFC3339Nano),
"result": status,
"real_send_attempted": false,
},
}
}

View File

@@ -0,0 +1,187 @@
package tools
import (
"context"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
func TestISphereSendFilePreviewComputesHashAndSize(t *testing.T) {
allowedDir := t.TempDir()
filePath := filepath.Join(allowedDir, "hello.txt")
if err := os.WriteFile(filePath, []byte("hello"), 0o600); err != nil {
t.Fatalf("write fixture file: %v", err)
}
t.Setenv(EnvSendFileAllowedDir, allowedDir)
session, cleanup := connectToolsTestSession(t, func(server *mcp.Server) {
RegisterISphereSendFileTool(server)
})
defer cleanup()
callResult, err := session.CallTool(context.Background(), &mcp.CallToolParams{
Name: ToolNameSendFile,
Arguments: map[string]any{
"target_type": "direct",
"target_id": "alice@imopenfire1-lanzhou",
"file_path": filePath,
"file_sha256": sha256HexForSendMessageTest("hello"),
"idempotency_key": "file-preview-idem-1",
"execution_mode": "preview",
"preview": true,
},
})
if err != nil {
t.Fatalf("call %s: %v", ToolNameSendFile, err)
}
if callResult.IsError {
t.Fatalf("preview should be structured success, got error: %+v", callResult)
}
var decoded struct {
OK bool `json:"ok"`
SendStatus string `json:"send_status"`
FileSHA256 string `json:"file_sha256"`
FileSizeBytes int64 `json:"file_size_bytes"`
TargetRef string `json:"target_ref"`
ProductionSendEnabled bool `json:"production_send_enabled"`
RealSendAttempted bool `json:"real_send_attempted"`
SideEffectFlags map[string]any `json:"side_effect_flags"`
}
payload, _ := json.Marshal(callResult.StructuredContent)
if err := json.Unmarshal(payload, &decoded); err != nil {
t.Fatalf("decode send-file preview payload %s: %v", payload, err)
}
if !decoded.OK || decoded.SendStatus != "planned" {
t.Fatalf("preview status mismatch: %s", payload)
}
if decoded.FileSHA256 != sha256HexForSendMessageTest("hello") || decoded.FileSizeBytes != 5 {
t.Fatalf("file metadata mismatch: %s", payload)
}
if decoded.TargetRef != "contact:alice@imopenfire1-lanzhou" {
t.Fatalf("target_ref = %q, want contact ref", decoded.TargetRef)
}
if decoded.ProductionSendEnabled || decoded.RealSendAttempted {
t.Fatalf("preview must not enable or attempt real send: %s", payload)
}
if decoded.SideEffectFlags["sent_file"] != false || decoded.SideEffectFlags["uploaded_file"] != false || decoded.SideEffectFlags["clicked_ui"] != false {
t.Fatalf("side-effect flags mismatch: %#v", decoded.SideEffectFlags)
}
}
func TestISphereSendFileRejectsPathOutsideAllowedDir(t *testing.T) {
allowedDir := t.TempDir()
outsideDir := t.TempDir()
filePath := filepath.Join(outsideDir, "outside.txt")
if err := os.WriteFile(filePath, []byte("outside"), 0o600); err != nil {
t.Fatalf("write outside fixture file: %v", err)
}
t.Setenv(EnvSendFileAllowedDir, allowedDir)
session, cleanup := connectToolsTestSession(t, func(server *mcp.Server) {
RegisterISphereSendFileTool(server)
})
defer cleanup()
callResult, err := session.CallTool(context.Background(), &mcp.CallToolParams{
Name: ToolNameSendFile,
Arguments: map[string]any{
"target_type": "group",
"target_id": "project-room@conference.imopenfire1-lanzhou",
"file_path": filePath,
"file_sha256": sha256HexForSendMessageTest("outside"),
"idempotency_key": "file-outside-idem-1",
"execution_mode": "preview",
"preview": true,
},
})
if err != nil {
t.Fatalf("call %s: %v", ToolNameSendFile, err)
}
if callResult.IsError {
t.Fatalf("outside path should be structured blocked metadata, got error: %+v", callResult)
}
var decoded struct {
OK bool `json:"ok"`
SendStatus string `json:"send_status"`
BlockedReason string `json:"blocked_reason"`
TargetRef string `json:"target_ref"`
SideEffectFlags map[string]any `json:"side_effect_flags"`
}
payload, _ := json.Marshal(callResult.StructuredContent)
if err := json.Unmarshal(payload, &decoded); err != nil {
t.Fatalf("decode outside-path payload %s: %v", payload, err)
}
if decoded.OK || decoded.SendStatus != "blocked" {
t.Fatalf("outside path should be blocked: %s", payload)
}
if !strings.Contains(decoded.BlockedReason, EnvSendFileAllowedDir) {
t.Fatalf("blocked reason should mention allowed-dir env: %q", decoded.BlockedReason)
}
if decoded.TargetRef != "group:project-room@conference.imopenfire1-lanzhou" {
t.Fatalf("target_ref = %q, want group ref", decoded.TargetRef)
}
if decoded.SideEffectFlags["sent_file"] != false || decoded.SideEffectFlags["uploaded_file"] != false || decoded.SideEffectFlags["typed_text"] != false {
t.Fatalf("blocked path should have no side effects: %#v", decoded.SideEffectFlags)
}
}
func TestISphereSendFileProductionBlockedWithoutSideEffects(t *testing.T) {
allowedDir := t.TempDir()
filePath := filepath.Join(allowedDir, "blocked.txt")
if err := os.WriteFile(filePath, []byte("blocked"), 0o600); err != nil {
t.Fatalf("write blocked fixture file: %v", err)
}
t.Setenv(EnvSendFileAllowedDir, allowedDir)
session, cleanup := connectToolsTestSession(t, func(server *mcp.Server) {
RegisterISphereSendFileTool(server)
})
defer cleanup()
callResult, err := session.CallTool(context.Background(), &mcp.CallToolParams{
Name: ToolNameSendFile,
Arguments: map[string]any{
"target_type": "direct",
"target_id": "alice@imopenfire1-lanzhou",
"file_path": filePath,
"file_sha256": sha256HexForSendMessageTest("blocked"),
"idempotency_key": "file-production-idem-1",
"execution_mode": "production",
},
})
if err != nil {
t.Fatalf("call %s production: %v", ToolNameSendFile, err)
}
if callResult.IsError {
t.Fatalf("production should be structured blocked metadata, got error: %+v", callResult)
}
var decoded struct {
OK bool `json:"ok"`
SendStatus string `json:"send_status"`
BlockedReason string `json:"blocked_reason"`
ProductionSendEnabled bool `json:"production_send_enabled"`
RealSendAttempted bool `json:"real_send_attempted"`
SideEffectFlags map[string]any `json:"side_effect_flags"`
}
payload, _ := json.Marshal(callResult.StructuredContent)
if err := json.Unmarshal(payload, &decoded); err != nil {
t.Fatalf("decode production-blocked payload %s: %v", payload, err)
}
if decoded.OK || decoded.SendStatus != "blocked" || decoded.BlockedReason == "" {
t.Fatalf("production should be blocked with reason: %s", payload)
}
if decoded.ProductionSendEnabled || decoded.RealSendAttempted {
t.Fatalf("production must not be enabled or attempted: %s", payload)
}
if decoded.SideEffectFlags["sent_file"] != false || decoded.SideEffectFlags["uploaded_file"] != false || decoded.SideEffectFlags["captured_network"] != false {
t.Fatalf("production blocked should have no side effects: %#v", decoded.SideEffectFlags)
}
}

View File

@@ -11,6 +11,7 @@ $expectedTools = @(
"isphere_search_contacts",
"isphere_search_groups",
"isphere_receive_files",
"isphere_send_file",
"isphere_send_message"
)
@@ -89,6 +90,7 @@ var expectedTools = []string{
"isphere_search_contacts",
"isphere_search_groups",
"isphere_receive_files",
"isphere_send_file",
"isphere_send_message",
}
@@ -98,7 +100,7 @@ func main() {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
for _, key := range []string{"ISPHERE_PACKET_LOG_FILE", "ISPHERE_PACKET_LOG_DIR", "ISPHERE_MSGLIB_SIDECAR_EXE", "ISPHERE_MSGLIB_SQLITE_DLL", "ISPHERE_MSGLIB_DB", "ISPHERE_MSGLIB_PASSWORD"} {
for _, key := range []string{"ISPHERE_PACKET_LOG_FILE", "ISPHERE_PACKET_LOG_DIR", "ISPHERE_MSGLIB_SIDECAR_EXE", "ISPHERE_MSGLIB_SQLITE_DLL", "ISPHERE_MSGLIB_DB", "ISPHERE_MSGLIB_PASSWORD", "ISPHERE_SEND_FILE_ALLOWED_DIR"} {
if err := os.Unsetenv(key); err != nil {
fail("server/env", err)
}
@@ -114,6 +116,18 @@ func main() {
if err := os.Setenv("ISPHERE_SEND_IDEMPOTENCY_PATH", filepath.Join(sendStateDir, "send-idempotency.jsonl")); err != nil {
fail("server/send_state", err)
}
sendFileDir, err := os.MkdirTemp("", "isphere-send-file-*")
if err != nil {
fail("server/send_file_state", err)
}
defer os.RemoveAll(sendFileDir)
sendFilePath := filepath.Join(sendFileDir, "redacted-preview.txt")
if err := os.WriteFile(sendFilePath, []byte("hello"), 0o600); err != nil {
fail("server/send_file_state", err)
}
if err := os.Setenv("ISPHERE_SEND_FILE_ALLOWED_DIR", sendFileDir); err != nil {
fail("server/send_file_state", err)
}
serverTransport, clientTransport := mcp.NewInMemoryTransports()
server, err := mcpserver.NewServerFromEnv()
@@ -158,7 +172,7 @@ func main() {
sort.Strings(toolNames)
want := append([]string(nil), expectedTools...)
sort.Strings(want)
if len(toolNames) != 9 || !reflect.DeepEqual(toolNames, want) {
if len(toolNames) != 10 || !reflect.DeepEqual(toolNames, want) {
fail("tools/list", fmt.Errorf("tool names = %#v, want %#v", toolNames, want))
}
@@ -221,6 +235,7 @@ func main() {
defaultGroupCount := verifySearchGroups(ctx, session, "project", "tools/call isphere_search_groups default", 0)
defaultFileCount := verifyReceiveFiles(ctx, session, "report", "tools/call isphere_receive_files default", 0, "", "")
sendPreviewOK, productionSendEnabled := verifySendMessagePreview(ctx, session)
sendFilePreviewOK, sendFileProductionEnabled := verifySendFilePreview(ctx, session, sendFilePath)
configuredReceiveCount, configuredContactCount, configuredGroupCount, configuredFileCount := verifyConfiguredReceiveSource(ctx)
configuredDirReceiveCount, configuredDirContactCount, configuredDirGroupCount, configuredDirFileCount := verifyConfiguredDirectorySource(ctx)
@@ -250,6 +265,8 @@ func main() {
"action_tools_present": false,
"send_preview_tool_present": sendPreviewOK,
"production_send_enabled": productionSendEnabled,
"send_file_preview_tool_present": sendFilePreviewOK,
"send_file_production_enabled": sendFileProductionEnabled,
"msglib_configured": false,
}
encoded, _ := json.Marshal(result)
@@ -569,6 +586,68 @@ func verifySendMessagePreview(ctx context.Context, session *mcp.ClientSession) (
return true, false
}
func verifySendFilePreview(ctx context.Context, session *mcp.ClientSession, filePath string) (bool, bool) {
fileHash := sha256FileHexForHarness(filePath)
callResult, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "isphere_send_file", Arguments: map[string]any{
"target_type": "direct",
"target_id": "sender@imopenfire1-lanzhou",
"file_path": filePath,
"file_sha256": fileHash,
"idempotency_key": "verify-file-preview-idempotency-key",
"execution_mode": "preview",
"preview": true,
}})
if err != nil {
fail("tools/call isphere_send_file preview", err)
}
if callResult.IsError {
fail("tools/call isphere_send_file preview", fmt.Errorf("tool returned isError=true: %#v", callResult.Content))
}
var previewPayload map[string]any
encoded, _ := json.Marshal(callResult.StructuredContent)
if err := json.Unmarshal(encoded, &previewPayload); err != nil {
fail("tools/call isphere_send_file preview", fmt.Errorf("decode structuredContent %s: %w", encoded, err))
}
if previewPayload["ok"] != true || previewPayload["send_status"] != "planned" || previewPayload["file_sha256"] != fileHash || previewPayload["file_size_bytes"] != float64(5) {
fail("tools/call isphere_send_file preview", fmt.Errorf("unexpected send-file preview status: %s", encoded))
}
if previewPayload["production_send_enabled"] != false || previewPayload["real_send_attempted"] != false {
fail("tools/call isphere_send_file preview", fmt.Errorf("send-file preview should not enable or attempt send: %s", encoded))
}
sideEffects, ok := previewPayload["side_effect_flags"].(map[string]any)
if !ok || sideEffects["sent_file"] != false || sideEffects["uploaded_file"] != false || sideEffects["clicked_ui"] != false {
fail("tools/call isphere_send_file preview", fmt.Errorf("unexpected send-file side effects: %s", encoded))
}
productionResult, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "isphere_send_file", Arguments: map[string]any{
"target_type": "direct",
"target_id": "sender@imopenfire1-lanzhou",
"file_path": filePath,
"file_sha256": fileHash,
"idempotency_key": "verify-file-production-idempotency-key",
"execution_mode": "production",
}})
if err != nil {
fail("tools/call isphere_send_file production_blocked", err)
}
if productionResult.IsError {
fail("tools/call isphere_send_file production_blocked", fmt.Errorf("tool returned isError=true: %#v", productionResult.Content))
}
var productionPayload map[string]any
productionEncoded, _ := json.Marshal(productionResult.StructuredContent)
if err := json.Unmarshal(productionEncoded, &productionPayload); err != nil {
fail("tools/call isphere_send_file production_blocked", fmt.Errorf("decode structuredContent %s: %w", productionEncoded, err))
}
if productionPayload["ok"] != false || productionPayload["send_status"] != "blocked" || productionPayload["production_send_enabled"] != false || productionPayload["real_send_attempted"] != false {
fail("tools/call isphere_send_file production_blocked", fmt.Errorf("production file send was not blocked: %s", productionEncoded))
}
productionSideEffects, ok := productionPayload["side_effect_flags"].(map[string]any)
if !ok || productionSideEffects["sent_file"] != false || productionSideEffects["uploaded_file"] != false || productionSideEffects["captured_network"] != false {
fail("tools/call isphere_send_file production_blocked", fmt.Errorf("unexpected production file side effects: %s", productionEncoded))
}
return true, false
}
func verifySearchContacts(ctx context.Context, session *mcp.ClientSession, query string, step string, wantCount int) int {
callResult, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "isphere_search_contacts", Arguments: map[string]any{
"query": query,
@@ -716,6 +795,14 @@ func sha256HexForHarness(value string) string {
return hex.EncodeToString(sum[:])
}
func sha256FileHexForHarness(path string) string {
payload, err := os.ReadFile(path)
if err != nil {
fail("fixture/file_hash", err)
}
return sha256HexForHarness(string(payload))
}
func padPKCS7ForHarness(data []byte, blockSize int) []byte {
pad := blockSize - len(data)%blockSize
out := append([]byte(nil), data...)
@@ -752,7 +839,7 @@ func fail(step string, err error) {
Assert-True ($script:harnessJson.ok -eq $true) "SDK harness did not return ok=true"
Assert-True ($script:harnessJson.helper_name -eq "ISphereWinHelper") "SDK harness helper_name mismatch: $($script:harnessJson.helper_name)"
Assert-True ($script:harnessJson.tool_count -eq 9) "SDK harness tool_count mismatch: $($script:harnessJson.tool_count)"
Assert-True ($script:harnessJson.tool_count -eq 10) "SDK harness tool_count mismatch: $($script:harnessJson.tool_count)"
Assert-True ($script:harnessJson.receive_message_count -eq 0) "SDK harness receive_message_count mismatch: $($script:harnessJson.receive_message_count)"
Assert-True ($script:harnessJson.contact_count -eq 0) "SDK harness contact_count mismatch: $($script:harnessJson.contact_count)"
Assert-True ($script:harnessJson.group_count -eq 0) "SDK harness group_count mismatch: $($script:harnessJson.group_count)"
@@ -767,6 +854,8 @@ func fail(step string, err error) {
Assert-True ($script:harnessJson.configured_dir_file_count -eq 1) "SDK harness configured_dir_file_count mismatch: $($script:harnessJson.configured_dir_file_count)"
Assert-True ($script:harnessJson.send_preview_tool_present -eq $true) "SDK harness send_preview_tool_present mismatch: $($script:harnessJson.send_preview_tool_present)"
Assert-True ($script:harnessJson.production_send_enabled -eq $false) "SDK harness production_send_enabled mismatch: $($script:harnessJson.production_send_enabled)"
Assert-True ($script:harnessJson.send_file_preview_tool_present -eq $true) "SDK harness send_file_preview_tool_present mismatch: $($script:harnessJson.send_file_preview_tool_present)"
Assert-True ($script:harnessJson.send_file_production_enabled -eq $false) "SDK harness send_file_production_enabled mismatch: $($script:harnessJson.send_file_production_enabled)"
[ordered]@{
ok = $true
@@ -789,6 +878,8 @@ func fail(step string, err error) {
configured_dir_file_count = $script:harnessJson.configured_dir_file_count
send_preview_tool_present = $script:harnessJson.send_preview_tool_present
production_send_enabled = $script:harnessJson.production_send_enabled
send_file_preview_tool_present = $script:harnessJson.send_file_preview_tool_present
send_file_production_enabled = $script:harnessJson.send_file_production_enabled
packet_log_file_configured = $script:harnessJson.packet_log_file_configured
packet_log_dir_configured = $script:harnessJson.packet_log_dir_configured
python_runtime_required = $false