Skip to content

feat: mock record/replay and mcp support#3714

Open
anjupathak03 wants to merge 43 commits intomainfrom
mcp-support
Open

feat: mock record/replay and mcp support#3714
anjupathak03 wants to merge 43 commits intomainfrom
mcp-support

Conversation

@anjupathak03
Copy link
Contributor

@anjupathak03 anjupathak03 commented Feb 3, 2026

Describe the changes that are made

This pull request introduces a new mcp (Model Context Protocol) command to the CLI, enabling Keploy to be used as an MCP server for AI assistant integrations (e.g., VS Code, Claude Desktop). It also refactors the mock command structure, adds dedicated mock record and mock test subcommands, and improves command flag handling, logging, and MCP-specific behaviors for robust stdio-based operation.

The most important changes are:

MCP Server Integration

  • Added a new cli/mcp.go file implementing the mcp command with a serve subcommand, which starts a Keploy MCP server over stdio using JSON-RPC 2.0, with robust logging to stderr and log files, and explicit handling to prevent stdout pollution. This enables integration with AI assistants that support MCP.
  • Introduced a new logger (newMCPLogger) that outputs only structured JSON logs to stderr (and optionally to file), with no ANSI color codes, to comply with MCP protocol requirements.

Mock Command Enhancements

  • Refactored the mock command to add dedicated mock record and mock test subcommands, each with their own flag handling and logic, making it easier to record and replay mocks via CLI. [1] [2]
  • Added detailed implementations for MockRecord and MockTest commands, including argument parsing, service initialization, and structured logging of results.

Command Flag and Validation Improvements

  • Enhanced CmdConfigurator to add flags contextually for the new mock record and mock test subcommands, and improved normalization for new flags (e.g., mock-name). [1] [2]
  • Introduced the isMCPStdioCommand helper and MCPStdioAnnotationKey constant to identify MCP commands and adjust validation, error handling, and logger configuration accordingly. [1] [2] [3]
  • Ensured that ANSI color output and logo printing are disabled for MCP commands to avoid corrupting the JSON-RPC stream, and that logger behavior is adjusted for MCP and non-MCP commands. [1] [2]

Logging and Output Handling

  • Improved logger configuration to ensure that, for MCP commands, all logs go to stderr in structured JSON format, and that the logger is properly initialized at the correct level based on debug flags. [1] [2] [3]
  • Added logic to save both stdout (JSON-RPC messages) and stderr (logs) to timestamped log files for debugging, which is crucial when integrating with AI assistants that consume these streams.

General Codebase Improvements

  • Updated import statements and code structure to support new features and maintain code clarity.

These changes significantly enhance Keploy's CLI by enabling robust AI assistant integrations, improving mock management, and ensuring reliable, protocol-compliant operation for MCP scenarios.

Links & References

Closes: #[issue number that will be closed through this PR]

  • NA (if very small change like typo, linting, etc.)

🔗 Related PRs

  • NA

🐞 Related Issues

  • NA

📄 Related Documents

  • NA

What type of PR is this? (check all applicable)

  • 📦 Chore
  • 🍕 Feature
  • 🐞 Bug Fix
  • 📝 Documentation Update
  • 🎨 Style
  • 🧑‍💻 Code Refactor
  • 🔥 Performance Improvements
  • ✅ Test
  • 🔁 CI
  • ⏩ Revert

Added e2e test pipeline?

  • 👍 yes
  • 🙅 no, because they aren't needed
  • 🙋 no, because I need help

Added comments for hard-to-understand areas?

  • 👍 yes
  • 🙅 no, because the code is self-explanatory

Added to documentation?

  • 📜 README.md
  • 📓 Wiki
  • 🙅 no documentation needed

Are there any sample code or steps to test the changes?

  • 👍 yes, mentioned below
  • 🙅 no, because it is not needed

Self Review done?

  • ✅ yes
  • ❌ no, because I need help

Any relevant screenshots, recordings or logs?

  • NA

🧠 Semantics for PR Title & Branch Name

Please ensure your PR title and branch name follow the Keploy semantics:

📌 PR Semantics Guide
📌 Branch Semantics Guide

Examples:

  • PR Title: fix: patch MongoDB document update bug
  • Branch Name: feat/#1-login-flow (You may skip mentioning the issue number in the branch name if the change is small and the PR description clearly explains it.)

Additional checklist:

commit 1e8a6aa
Author: Anju Pathak <[email protected]>
Date:   Tue Feb 3 16:48:19 2026 +0000

    fix: build

    Signed-off-by: Anju Pathak <[email protected]>

commit ddc79d6
Merge: aca4f56 3abdd5f
Author: Anju Pathak <[email protected]>
Date:   Tue Feb 3 16:47:21 2026 +0000

    Merge branch 'main' into mcp-server-pipeline

commit aca4f56
Author: Anju <[email protected]>
Date:   Fri Jan 30 05:41:52 2026 +0530

    updated the automatic pipeline creation

    Signed-off-by: Anju <[email protected]>

commit 3af87bf
Author: Anju <[email protected]>
Date:   Thu Jan 29 16:23:15 2026 +0530

    feat(mcp): add keploy_manager tool with pipeline generation

    Signed-off-by: Anju <[email protected]>

commit 4ed8cc9
Merge: da2d32a fdf5d57
Author: Anju <[email protected]>
Date:   Tue Jan 27 23:33:20 2026 +0530

    Merge branch 'fix-mysql-parser' into mock-record-replay-mcp

commit da2d32a
Merge: 726de11 5bcc7ab
Author: Anju <[email protected]>
Date:   Tue Jan 27 23:30:19 2026 +0530

    Merge branch 'main' into mock-record-replay-mcp

commit fdf5d57
Author: Anju <[email protected]>
Date:   Tue Jan 27 17:49:35 2026 +0530

    fix: lint

    Signed-off-by: Anju <[email protected]>

commit 51842f2
Author: Anju <[email protected]>
Date:   Tue Jan 27 17:46:27 2026 +0530

    fix: lint

    Signed-off-by: Anju <[email protected]>

commit 59d3f07
Author: Anju <[email protected]>
Date:   Tue Jan 27 17:37:11 2026 +0530

    fix: date/time binary length handling

    Signed-off-by: Anju <[email protected]>

commit 272110c
Author: Anju <[email protected]>
Date:   Tue Jan 27 17:34:38 2026 +0530

    fix: HandshakeResponse41 auth-response decoding

    Signed-off-by: Anju <[email protected]>

commit da9ac85
Author: Anju <[email protected]>
Date:   Tue Jan 27 17:26:53 2026 +0530

    fix: Correctly decode 0x02 as auth or COM_INIT_DB based on context

    Signed-off-by: Anju <[email protected]>

commit 726de11
Author: Anju <[email protected]>
Date:   Fri Jan 23 16:05:49 2026 +0530

    fix: MCP path resolution and use independent context for server lifecycle

    Signed-off-by: Anju <[email protected]>

commit a4433bb
Author: Anju <[email protected]>
Date:   Fri Jan 23 15:39:36 2026 +0530

    fix: MySQL read timeout and og actual SQL for prepared statements

    Signed-off-by: Anju <[email protected]>

commit 151ba6b
Author: Anju <[email protected]>
Date:   Wed Jan 21 18:13:21 2026 +0530

    fix: improved the debugging experience during mock replay

    Signed-off-by: Anju <[email protected]>

commit 672ec6c
Author: Anju <[email protected]>
Date:   Wed Jan 21 18:10:12 2026 +0530

    fix: console output interleaving

    Signed-off-by: Anju <[email protected]>

commit afef355
Author: Anju <[email protected]>
Date:   Wed Jan 21 18:07:50 2026 +0530

    fix: --duration flag working for the mock record command and duplicate logo

    Signed-off-by: Anju <[email protected]>

commit 35ffa13
Author: Anju <[email protected]>
Date:   Wed Jan 21 18:01:26 2026 +0530

    fix: Suppress Windows sharing violation on delete, avoid logging to a closed log file.

    Signed-off-by: Anju <[email protected]>

commit f7832f5
Author: Anju <[email protected]>
Date:   Wed Jan 21 17:58:49 2026 +0530

    fix: Treat TLS close‑notify and use of closed network connection as benign.

    Signed-off-by: Anju <[email protected]>

commit c163133
Author: Anju <[email protected]>
Date:   Wed Jan 21 17:43:05 2026 +0530

    fix: No goroutine blocking, Both success and error cases are communicated through the channel

    Signed-off-by: Anju <[email protected]>

commit 0525b8b
Author: Anju <[email protected]>
Date:   Wed Jan 21 17:31:43 2026 +0530

    fix: resolved Windows incoming traffic interception issue

    Signed-off-by: Anju <[email protected]>

commit 4671660
Author: Anju Pathak <[email protected]>
Date:   Tue Jan 20 13:56:18 2026 +0530

    fix: merge conflict

    Signed-off-by: Anju Pathak <[email protected]>

commit 9952088
Merge: b82f4d9 36d1a98
Author: Anju <[email protected]>
Date:   Tue Jan 20 13:34:53 2026 +0530

    Merge branch 'main' into mock-record-replay-mcp

commit b82f4d9
Author: Anju Pathak <[email protected]>
Date:   Thu Jan 15 11:57:06 2026 +0530

    Revert "fix(windows): app exit signal not propagating to agent"

    This reverts commit 2fcf4f2.

commit 12c6c1f
Author: Anju <[email protected]>
Date:   Wed Jan 7 16:40:14 2026 +0530

    fix(mcp): add log files, optional params & fs-based mock listing

    Signed-off-by: Anju <[email protected]>

commit 86e8cbc
Author: Anju <[email protected]>
Date:   Tue Jan 6 14:01:33 2026 +0530

    fix: mcp serve command, suppress logo output for JSON-RPC

    Signed-off-by: Anju <[email protected]>

commit 157ae0f
Author: Anju Pathak <[email protected]>
Date:   Mon Jan 5 07:48:26 2026 +0000

    docs(mcp): Update API reference, architecture, and user guide for protocol version and path descriptions

    Signed-off-by: Anju Pathak <[email protected]>

commit 2fcf4f2
Author: Anju Pathak <[email protected]>
Date:   Mon Jan 5 07:41:57 2026 +0000

    fix(windows): app exit signal not propagating to agent

    Signed-off-by: Anju Pathak <[email protected]>

commit e2573d3
Author: Anju Pathak <[email protected]>
Date:   Mon Jan 5 07:21:36 2026 +0000

    feat(mcp): Enhance MCP server for JSON-RPC compliance and add list mocks tool

    - Updated MCP server to ensure JSON-RPC 2.0 compliance by enforcing output to stderr and avoiding ANSI codes.
    - Introduced a new logger specifically for MCP that adheres to the compliance requirements.
    - Added  tool to list available mock sets, improving user interaction and mock discovery.
    - Enhanced mock record and replay tools with better configuration handling and user feedback.
    - Refactored output handling in the agent to support MCP stdio mode.
    - Removed outdated README files for mock recording and replay services.
    - Added utility functions to manage MCP stdio mode state.

    Signed-off-by: Anju Pathak <[email protected]>

commit 4bb3df9
Author: Anju Pathak <[email protected]>
Date:   Mon Jan 5 04:39:09 2026 +0000

    Refactor mock replay and recording services

    - Simplified the replayer service by removing unnecessary dependencies and integrating runtime configuration.
    - Introduced a new Runtime interface to provide shared state access for replay operations.
    - Removed the AgentService and MockDB interfaces from the replayer, consolidating functionality.
    - Streamlined the Replay method to focus on essential operations, delegating mock loading and command execution.
    - Added a new command package to infer container names from Docker commands.
    - Removed the mock_record.go file and replaced its functionality with a more modular approach in the record service.
    - Enhanced the Start method in the Recorder to support flexible recording options and improved error handling.
    - Updated the service interfaces to reflect the changes in the recording and replay logic.
    - Introduced new options for recording sessions, allowing for better customization and control over the recording process.

    Signed-off-by: Anju Pathak <[email protected]>

commit 0c11e0b
Author: Anju Pathak <[email protected]>
Date:   Mon Jan 5 01:05:51 2026 +0000

    refactor to reuse record with a mock‑only mode.

    Signed-off-by: Anju Pathak <[email protected]>

commit cc63787
Merge: 29324ff 1623cb1
Author: Anju Pathak <[email protected]>
Date:   Fri Jan 2 07:18:10 2026 +0000

    Merge branch 'feat/windows-redirect' into mock-record-replay-mcp

commit 29324ff
Author: Anju Pathak <[email protected]>
Date:   Fri Jan 2 07:11:23 2026 +0000

    feat: Implement mock recording and replay services

    - Added `mockrecord` service for capturing and storing outgoing calls during application execution.
    - Introduced `MockRecordInput` and `MockRecordOutput` types for handling mock recording requests and responses.
    - Implemented `handleMockRecord` function to manage the recording process, including command execution and mock storage.
    - Created `mockreplay` service for replaying recorded mocks during testing.
    - Added `MockReplayInput` and `MockReplayOutput` types for managing mock replay requests and responses.
    - Implemented `handleMockReplay` function to handle the replay process, including loading mocks and executing application commands.
    - Developed metadata extraction logic for contextual naming of recorded mocks.
    - Added YAML parsing for loading mocks from files, supporting both file and directory paths.
    - Enhanced logging for better traceability during recording and replay processes.
    - Updated README files for both services to provide usage instructions and architectural overview.

    Signed-off-by: Anju Pathak <[email protected]>

commit 1623cb1
Author: Anju Pathak <[email protected]>
Date:   Mon Dec 22 00:19:07 2025 +0000

    fix: add private parsers

    Signed-off-by: Anju Pathak <[email protected]>

commit 0a66246
Author: Anju Pathak <[email protected]>
Date:   Sun Dec 21 20:30:04 2025 +0000

    fix: use local mongo

    Signed-off-by: Anju Pathak <[email protected]>

commit 1c85b49
Author: Anju <[email protected]>
Date:   Mon Dec 22 01:47:26 2025 +0530

    fix(windows): resolve path issues

    Signed-off-by: Anju <[email protected]>

commit 09e1d6a
Author: Anju <[email protected]>
Date:   Sun Dec 21 22:40:12 2025 +0530

    fix(windows): resolve path issues for native tests

    Signed-off-by: Anju <[email protected]>

commit 587421c
Author: Anju <[email protected]>
Date:   Sun Dec 21 22:13:26 2025 +0530

    fix(windows): resolve path issues for native tests

    Signed-off-by: Anju <[email protected]>

commit f102417
Author: Anju <[email protected]>
Date:   Sun Dec 21 21:46:09 2025 +0530

    fix(windows): resolve path issues for native tests

    Signed-off-by: Anju <[email protected]>

commit 5cfbacd
Author: Anju <[email protected]>
Date:   Sun Dec 21 21:18:39 2025 +0530

    fix: pre-build to avoid timeout

    Signed-off-by: Anju <[email protected]>

commit 4ba0ab1
Author: Anju <[email protected]>
Date:   Sun Dec 21 21:00:31 2025 +0530

    fix: pre-build to avoid timeout

    Signed-off-by: Anju <[email protected]>

commit 809edc9
Merge: d21e555 51ff0e5
Author: Anju <[email protected]>
Date:   Sun Dec 21 20:01:31 2025 +0530

    Merge branch 'main' into feat/windows-redirect

commit d21e555
Author: Anju <[email protected]>
Date:   Sat Dec 20 03:06:43 2025 +0530

    fix(ci): enhance gin-mongo Windows test script for GitHub Actions

    Signed-off-by: Anju <[email protected]>

commit a27cbce
Author: Anju <[email protected]>
Date:   Fri Dec 19 04:16:16 2025 +0530

    Update pkg/agent/hooks/windows/redirector.go

    Co-authored-by: Copilot <[email protected]>
    Signed-off-by: Anju <[email protected]>

commit 0d55523
Author: Anju <[email protected]>
Date:   Fri Dec 19 04:05:59 2025 +0530

    fix: Windows workflow syntax errors

    Signed-off-by: Anju <[email protected]>

commit 48038c9
Author: Anju <[email protected]>
Date:   Fri Dec 19 03:43:31 2025 +0530

    fix: Windows workflow syntax errors

    Signed-off-by: Anju <[email protected]>

commit 70a90ac
Author: Anju <[email protected]>
Date:   Fri Dec 19 03:40:48 2025 +0530

    fix: Windows workflow syntax errors

    Signed-off-by: Anju <[email protected]>

commit 9ad4a87
Author: Anju <[email protected]>
Date:   Fri Dec 19 03:31:48 2025 +0530

    feat: added pipeline native Windows support

    Signed-off-by: Anju <[email protected]>

commit 620ea47
Author: Anju <[email protected]>
Date:   Fri Dec 19 02:47:07 2025 +0530

    Remove Docker image pull step from workflow

    Removed the step to pull Docker images from the workflow.

    Signed-off-by: Anju <[email protected]>

commit a3e443a
Author: Anju <[email protected]>
Date:   Fri Dec 19 02:32:01 2025 +0530

    fix: Windows workflow syntax errors

    Signed-off-by: Anju <[email protected]>

commit a1885f6
Author: Anju <[email protected]>
Date:   Fri Dec 19 01:20:40 2025 +0530

    fix: Windows workflow syntax errors

    Signed-off-by: Anju <[email protected]>

commit b6cae49
Author: Anju <[email protected]>
Date:   Fri Dec 19 01:10:37 2025 +0530

    fix: Windows workflow syntax errors

    Signed-off-by: Anju <[email protected]>

commit d77f79d
Author: Anju <[email protected]>
Date:   Fri Dec 19 00:53:35 2025 +0530

    fix: Windows workflow syntax errors

    Signed-off-by: Anju <[email protected]>

commit b4f2a6b
Author: Anju <[email protected]>
Date:   Thu Dec 18 20:39:16 2025 +0530

    fix: Windows workflow syntax errors

    Signed-off-by: Anju <[email protected]>

commit 2affc7c
Author: Anju <[email protected]>
Date:   Thu Dec 18 20:05:48 2025 +0530

    fix: Windows workflow syntax errors

    Signed-off-by: Anju <[email protected]>

commit eb88853
Author: Anju <[email protected]>
Date:   Thu Dec 18 19:48:27 2025 +0530

    fix: typo error (gin-mongo)

    Signed-off-by: Anju <[email protected]>

commit f9643a4
Author: Anju <[email protected]>
Date:   Thu Dec 18 19:41:54 2025 +0530

    ci: add native Windows workflow (gin-mongo)

    Signed-off-by: Anju <[email protected]>

commit 6cef159
Merge: c223d17 c832f0e
Author: Anju <[email protected]>
Date:   Thu Dec 18 17:14:57 2025 +0530

    Merge remote changes from feat/windows-redirect

commit c223d17
Author: Anju <[email protected]>
Date:   Thu Dec 18 17:10:38 2025 +0530

    fix: Added MinGW gcc to PATH

    Signed-off-by: Anju <[email protected]>

commit c832f0e
Merge: 9841dc2 d99ebae
Author: Anju <[email protected]>
Date:   Thu Dec 18 17:00:56 2025 +0530

    Merge branch 'main' into feat/windows-redirect

commit 9841dc2
Merge: 8212ced 53d5c11
Author: Anju <[email protected]>
Date:   Thu Dec 18 16:59:22 2025 +0530

    Merge remote-tracking branch 'origin/feat/windows-redirect' into feat/windows-redirect

commit 8212ced
Author: Anju <[email protected]>
Date:   Thu Dec 18 16:56:01 2025 +0530

    fix: add CGO toolchain sanity check

    Signed-off-by: Anju <[email protected]>

commit 53d5c11
Author: Ayush Sharma <[email protected]>
Date:   Thu Dec 18 15:57:21 2025 +0530

    chore: remove integrations repo and sys file from the root

    Signed-off-by: Ayush Sharma <[email protected]>

commit c4cb270
Author: Anju <[email protected]>
Date:   Thu Dec 18 15:06:40 2025 +0530

    ci: added native Windows testing workflow on GitHub-hosted runners

    Signed-off-by: Anju <[email protected]>

commit a7bae92
Author: Anju <[email protected]>
Date:   Thu Dec 18 03:47:14 2025 +0530

    feat: Added Windows certificate installation support using certutil

    Signed-off-by: Anju <[email protected]>

commit 8f0719b
Merge: 0815003 ac9e9c2
Author: Anju <[email protected]>
Date:   Thu Dec 18 03:41:37 2025 +0530

    Merge remote-tracking branch 'origin/feat/windows-redirect' into feat/windows-redirect

commit ac9e9c2
Merge: ef6b7ba ae5d167
Author: Sarthak Shyngle <[email protected]>
Date:   Wed Dec 17 06:45:12 2025 -0800

    Merge branch 'main' into feat/windows-redirect

commit 0815003
Merge: 40f35b3 ef6b7ba
Author: Anju <[email protected]>
Date:   Wed Dec 17 19:13:16 2025 +0530

    Merge branch 'feat/windows-redirect' of github.com:keploy/keploy into feat/windows-redirect

commit ef6b7ba
Merge: 50ccd8e 86ad97c
Author: Anju <[email protected]>
Date:   Wed Dec 17 19:11:55 2025 +0530

    Merge branch 'main' into feat/windows-redirect

commit 40f35b3
Merge: 4ae2768 50ccd8e
Author: Anju <[email protected]>
Date:   Wed Dec 17 19:08:41 2025 +0530

    Merge branch 'feat/windows-redirect' of github.com:keploy/keploy into feat/windows-redirect

commit 50ccd8e
Author: Anju Pathak <[email protected]>
Date:   Wed Dec 17 13:18:14 2025 +0000

    fix: resolve SYS driver file not found by extracting WinDivert to exe directory

    Signed-off-by: Anju Pathak <[email protected]>

commit 4ae2768
Author: Anju <[email protected]>
Date:   Wed Dec 17 18:26:21 2025 +0530

    fix: resolve SYS driver file not found by extracting WinDivert to exe directory

    Signed-off-by: Anju <[email protected]>

commit b987eac
Merge: 3fd5857 c1d437a
Author: Anju <[email protected]>
Date:   Tue Dec 16 13:08:46 2025 +0530

    Merge branch 'main' into feat/windows-redirect

commit 3fd5857
Author: Ayush Sharma <[email protected]>
Date:   Fri Dec 12 12:27:23 2025 +0530

    fix: build issues

    Signed-off-by: Ayush Sharma <[email protected]>

commit 66a0851
Merge: b667c94 d157c5d
Author: Ayush Sharma <[email protected]>
Date:   Fri Dec 12 06:49:35 2025 +0000

    Merge branch 'main' into feat/windows-redirect

    Signed-off-by: Ayush Sharma <[email protected]>

commit b667c94
Author: Ayush Sharma <[email protected]>
Date:   Thu Nov 20 12:14:41 2025 +0000

    feat: add dns support for windows

    Signed-off-by: Ayush Sharma <[email protected]>

commit 4683cb4
Author: Ayush Sharma <[email protected]>
Date:   Thu Nov 20 14:15:33 2025 +0530

    fix: lint issues and enabled cgo for windows build

    Signed-off-by: Ayush Sharma <[email protected]>

commit a4785da
Author: Ayush Sharma <[email protected]>
Date:   Thu Nov 20 08:37:41 2025 +0000

    feat: do not run native on windows arm64 as windivert does not support

    Signed-off-by: Ayush Sharma <[email protected]>

commit f511fdd
Author: Ayush Sharma <[email protected]>
Date:   Wed Nov 19 16:27:39 2025 +0000

    feat: send dns port to the redirector

    Signed-off-by: Ayush Sharma <[email protected]>

commit 7c2fc3a
Merge: 18bc102 c161070
Author: Ayush Sharma <[email protected]>
Date:   Wed Nov 19 16:06:57 2025 +0000

    Merge remote-tracking branch 'origin/main' into feat/windows-redirect

    Signed-off-by: Ayush Sharma <[email protected]>

commit 18bc102
Author: Ayush Sharma <[email protected]>
Date:   Wed Nov 19 16:03:32 2025 +0000

    feat: remove the pipelines code

    Signed-off-by: Ayush Sharma <[email protected]>

commit 54152c9
Author: Ayush Sharma <[email protected]>
Date:   Wed Nov 19 15:55:26 2025 +0000

    feat: do cleanup of the previous approach

    Signed-off-by: Ayush Sharma <[email protected]>

commit e719b38
Author: Ayush Sharma <[email protected]>
Date:   Wed Nov 19 15:45:57 2025 +0000

    feat: use ffi functions for the go code

    Signed-off-by: Ayush Sharma <[email protected]>

commit 41af2c3
Author: Ayush Sharma <[email protected]>
Date:   Tue Nov 11 14:19:51 2025 +0530

    feat: increase the size of body of event

    Signed-off-by: Ayush Sharma <[email protected]>

commit 60caf5a
Author: Ayush Sharma <[email protected]>
Date:   Tue Nov 4 17:24:47 2025 +0530

    fix: keploy agent logs

    Signed-off-by: Ayush Sharma <[email protected]>

commit b8a04d9
Author: Ayush Sharma <[email protected]>
Date:   Tue Nov 4 17:00:37 2025 +0530

    fix: keploy agent logs

    Signed-off-by: Ayush Sharma <[email protected]>

commit 967da71
Author: Ayush Sharma <[email protected]>
Date:   Tue Nov 4 16:37:50 2025 +0530

    fix: kill keploy in windows pipeline

    Signed-off-by: Ayush Sharma <[email protected]>

commit 022718f
Author: Ayush Sharma <[email protected]>
Date:   Tue Nov 4 15:10:21 2025 +0530

    fix: kill keploy in windows pipeline

    Signed-off-by: Ayush Sharma <[email protected]>

commit 79b4630
Author: Ayush Sharma <[email protected]>
Date:   Tue Nov 4 13:38:40 2025 +0530

    chore: debug agent logs

    Signed-off-by: Ayush Sharma <[email protected]>

commit a7034d8
Author: Ayush Sharma <[email protected]>
Date:   Tue Nov 4 13:28:38 2025 +0530

    fix: windows pipeline

    Signed-off-by: Ayush Sharma <[email protected]>

commit 7a0b5d9
Merge: a3ec7e1 6c77cd0
Author: Ayush Sharma <[email protected]>
Date:   Tue Nov 4 13:00:35 2025 +0530

    Merge branch 'feat/windows-support-native' of https://github.com/keploy/keploy into feat/windows-support-native

    Signed-off-by: Ayush Sharma <[email protected]>

commit a3ec7e1
Author: Ayush Sharma <[email protected]>
Date:   Tue Nov 4 12:59:50 2025 +0530

    fix: run native pipeline

    Signed-off-by: Ayush Sharma <[email protected]>

commit 6c77cd0
Merge: 26758b1 abba501
Author: Ayush Sharma <[email protected]>
Date:   Tue Nov 4 12:45:21 2025 +0530

    Merge branch 'main' into feat/windows-support-native

commit 26758b1
Author: Ayush Sharma <[email protected]>
Date:   Tue Nov 4 12:43:35 2025 +0530

    feat: add windows native pipeline

    Signed-off-by: Ayush Sharma <[email protected]>

commit 5b01b06
Author: Ayush Sharma <[email protected]>
Date:   Tue Nov 4 12:24:54 2025 +0530

    fix: race condition

    Signed-off-by: Ayush Sharma <[email protected]>

commit 5d6289b
Author: Ayush Sharma <[email protected]>
Date:   Mon Nov 3 17:38:51 2025 +0530

    feat: add windows redirector binary

    Signed-off-by: Ayush Sharma <[email protected]>

commit b5f9958
Merge: adafe0e f5c619c
Author: Ayush Sharma <[email protected]>
Date:   Mon Nov 3 14:15:56 2025 +0530

    Merge branch 'feat/windows-support-native' of https://github.com/keploy/keploy into feat/windows-support-native

    Signed-off-by: Ayush Sharma <[email protected]>

commit f5c619c
Merge: a1b5981 7b31c4e
Author: Ayush Sharma <[email protected]>
Date:   Mon Nov 3 14:14:54 2025 +0530

    Merge branch 'main' into feat/windows-support-native

commit adafe0e
Author: Ayush Sharma <[email protected]>
Date:   Mon Nov 3 14:14:29 2025 +0530

    fix: app closing in windows

    Signed-off-by: Ayush Sharma <[email protected]>

commit a1b5981
Author: Ayush Sharma <[email protected]>
Date:   Fri Oct 31 14:56:09 2025 +0530

    fix: linux build

    Signed-off-by: Ayush Sharma <[email protected]>

commit 7d04af6
Author: Ayush Sharma <[email protected]>
Date:   Fri Oct 31 14:51:23 2025 +0530

    feat: make record work on windows

    Signed-off-by: Ayush Sharma <[email protected]>

commit c3a87d8
Author: Ayush Sharma <[email protected]>
Date:   Fri Oct 31 13:52:04 2025 +0530

    feat: make replay work for windows

    Signed-off-by: Ayush Sharma <[email protected]>

commit b123f92
Author: Ayush Sharma <[email protected]>
Date:   Thu Oct 30 17:39:30 2025 +0530

    feat: initialized windows support for windows

    Signed-off-by: Ayush Sharma <[email protected]>
Copilot AI review requested due to automatic review settings February 3, 2026 17:14
Signed-off-by: Anju Pathak <[email protected]>
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR adds comprehensive MCP (Model Context Protocol) server support to Keploy, enabling AI assistants to record and replay mocks through a JSON-RPC interface. The implementation includes new services for mock recording and replay, CLI commands, proper stdio/stderr handling for protocol compliance, and extensive documentation.

Changes:

  • Added MCP server implementation with three tools: list mocks, record mocks, and test/replay mocks
  • Created mockrecord and mockreplay services with configurable options
  • Fixed SQL delay conversion bug (multiplying by time.Second)
  • Enhanced MySQL query logging for better debugging
  • Added context management for long-lived MCP processes

Reviewed changes

Copilot reviewed 42 out of 44 changed files in this pull request and generated 9 comments.

Show a summary per file
File Description
pkg/mcp/* MCP server implementation with tool handlers, naming logic, and protocol management
pkg/service/mockrecord/* Mock recording service with metadata extraction
pkg/service/mockreplay/* Mock replay service with project detection
cli/mcp.go MCP CLI commands with stdio redirection
utils/ctx.go New MCP context for signal-only cancellation
pkg/service/replay/replay.go Fixed SQL delay conversion to seconds
pkg/agent/proxy/integrations/mysql/* Enhanced MySQL logging and handshake protocol
docs/mcp/* Comprehensive user guide, architecture, and API documentation

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +205 to +210
devNull, err := os.OpenFile(os.DevNull, os.O_WRONLY, 0)
if err != nil {
return err
}
defer devNull.Close()
os.Stdout = devNull
Copy link

Copilot AI Feb 3, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The os.Stdout redirection to /dev/null happens after capturing originalStdout, but if any code runs between lines 210 and 256 that writes to stdout, it will be lost. The MCP server initialization at line 256 depends on mcpStdoutWriter (line 260) which uses originalStdout. However, between lines 210-256, if serviceFactory.GetService or any initialization code writes to os.Stdout (which is now /dev/null), those writes are lost but don't corrupt the MCP stream. This is actually correct behavior, but consider adding a comment explaining this intentional redirection timing.

Copilot uses AI. Check for mistakes.
utils.LogError(a.logger, appErr.Err, "error while running the app")
appErrCh <- appErr
}
appErrCh <- appErr
Copy link

Copilot AI Feb 3, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The error at line 591 is now always sent to appErrCh (line 592), even when appErr.Err is nil. Previously, it only sent to the channel when err was not nil (line 590 in old code). This means a successful app execution (appErr.Err == nil) will now send an error to the channel, which could cause incorrect error handling. The logic should check if appErr.Err != nil before sending to appErrCh.

Suggested change
}
appErrCh <- appErr
appErrCh <- appErr
}

Copilot uses AI. Check for mistakes.
Comment on lines +42 to +56
func NewMCPCtx() context.Context {
ctx, cancel := context.WithCancel(context.Background())

// Listen for termination signals and cancel MCP context only on those.
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, os.Interrupt, syscall.SIGTERM)

go func() {
sig := <-sigs
fmt.Printf("MCP server: signal received: %s, shutting down...\n", sig)
cancel()
}()

return ctx
}
Copy link

Copilot AI Feb 3, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The NewMCPCtx creates a context that only listens to OS signals (Ctrl+C, SIGTERM) but doesn't respect cancellation from the parent context passed to server.Run(). This means if the parent context is cancelled for any reason other than OS signals, the MCP server will continue running. While this might be intentional for keeping the server alive across operations, it could lead to resource leaks if the parent context is cancelled due to application shutdown. Consider whether the MCP context should also respect parent context cancellation in addition to OS signals.

Copilot uses AI. Check for mistakes.
Comment on lines +666 to +705
func IP4StrToUint32(ipStr string) (uint32, error) {
// Split the IP address into its four octets.
octets := strings.Split(ipStr, ".")
if len(octets) != 4 {
return 0, fmt.Errorf("invalid IPv4 address format")
}

// Parse each octet as an integer and shift it to its correct position in the uint32.
var ip uint32
for i, octet := range octets {
octetInt, err := strconv.ParseUint(octet, 10, 8)
if err != nil {
return 0, fmt.Errorf("invalid octet %q in IP address: %v", octet, err)
}
ip |= uint32(octetInt) << (8 * uint(3-i))
}

return ip, nil
}

func IP6StrToUint32(ipStr string) ([4]uint32, error) {
// Parse the IPv6 address string
ip := net.ParseIP(ipStr)
if ip == nil || ip.To16() == nil {
return [4]uint32{}, fmt.Errorf("invalid IPv6 address format")
}

// Convert to a 16-byte representation
ip = ip.To16()

// Prepare the array to hold four uint32 values
var result [4]uint32

// Convert each 4-byte segment to a uint32
for i := 0; i < 4; i++ {
result[i] = binary.BigEndian.Uint32(ip[i*4 : (i+1)*4])
}

return result, nil
}
Copy link

Copilot AI Feb 3, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The IP4StrToUint32 and IP6StrToUint32 functions are added but there's no import for "binary" package which is used in IP6StrToUint32 at line 701. This will cause a compilation error. Add the missing import: "encoding/binary".

Copilot uses AI. Check for mistakes.
Rules: r.config.BypassRules,
MongoPassword: r.config.Test.MongoPassword,
SQLDelay: time.Duration(r.config.Test.Delay),
SQLDelay: time.Duration(r.config.Test.Delay) * time.Second,
Copy link

Copilot AI Feb 3, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The SQLDelay is being multiplied by time.Second here, but the config field might already be in seconds. This could result in double conversion if r.config.Test.Delay is already a duration type. Verify that r.config.Test.Delay is an integer representing seconds, not already a time.Duration.

Copilot uses AI. Check for mistakes.
Comment on lines +91 to +92
stdoutFile.Close()
return nil, nil, err
Copy link

Copilot AI Feb 3, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

File handle may be writable as a result of data flow from a call to OpenFile and closing it may result in data loss upon failure, which is not handled explicitly.

Suggested change
stdoutFile.Close()
return nil, nil, err
if cerr := stdoutFile.Close(); cerr != nil {
return nil, nil, fmt.Errorf("open stderr log file %q: %w; additionally failed to close stdout log file %q: %v", stderrPath, err, stdoutPath, cerr)
}
return nil, nil, fmt.Errorf("open stderr log file %q: %w", stderrPath, err)

Copilot uses AI. Check for mistakes.
Comment on lines +191 to +194
defer stdoutFile.Close()
}
if stderrFile != nil {
defer stderrFile.Close()
Copy link

Copilot AI Feb 3, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

File handle may be writable as a result of data flow from a call to OpenFile and closing it may result in data loss upon failure, which is not handled explicitly.

Suggested change
defer stdoutFile.Close()
}
if stderrFile != nil {
defer stderrFile.Close()
defer func(f *os.File) {
// Attempt to flush any buffered data before closing.
if err := f.Sync(); err != nil {
fmt.Fprintf(os.Stderr, `{"level":"warn","msg":"failed to sync MCP stdout log file: %v"}`+"\n", err)
}
if err := f.Close(); err != nil {
fmt.Fprintf(os.Stderr, `{"level":"error","msg":"failed to close MCP stdout log file: %v"}`+"\n", err)
}
}(stdoutFile)
}
if stderrFile != nil {
defer func(f *os.File) {
if err := f.Sync(); err != nil {
fmt.Fprintf(os.Stderr, `{"level":"warn","msg":"failed to sync MCP stderr log file: %v"}`+"\n", err)
}
if err := f.Close(); err != nil {
fmt.Fprintf(os.Stderr, `{"level":"error","msg":"failed to close MCP stderr log file: %v"}`+"\n", err)
}
}(stderrFile)

Copilot uses AI. Check for mistakes.
Comment on lines +191 to +194
defer stdoutFile.Close()
}
if stderrFile != nil {
defer stderrFile.Close()
Copy link

Copilot AI Feb 3, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

File handle may be writable as a result of data flow from a call to OpenFile and closing it may result in data loss upon failure, which is not handled explicitly.

Suggested change
defer stdoutFile.Close()
}
if stderrFile != nil {
defer stderrFile.Close()
defer func() {
if err := stdoutFile.Close(); err != nil {
fmt.Fprintf(os.Stderr, `{"level":"error","msg":"failed to close MCP stdout log file: %v"}`+"\n", err)
}
}()
}
if stderrFile != nil {
defer func() {
if err := stderrFile.Close(); err != nil {
fmt.Fprintf(os.Stderr, `{"level":"error","msg":"failed to close MCP stderr log file: %v"}`+"\n", err)
}
}()

Copilot uses AI. Check for mistakes.
if err != nil {
return err
}
defer devNull.Close()
Copy link

Copilot AI Feb 3, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

File handle may be writable as a result of data flow from a call to OpenFile and closing it may result in data loss upon failure, which is not handled explicitly.

Suggested change
defer devNull.Close()
defer func() {
if cerr := devNull.Close(); cerr != nil {
fmt.Fprintf(os.Stderr, `{"level":"warn","msg":"failed to close devNull: %v"}`+"\n", cerr)
}
}()

Copilot uses AI. Check for mistakes.
anjupathak03 and others added 5 commits February 4, 2026 02:42
Signed-off-by: Anju Pathak <[email protected]>
  The previous calculation  caused an
integer overflow when  was large (e.g., 5s), resulting in a negative read
deadline. This caused the proxy to immediately timeout connections during replay.

  This commit fixes the issue by simplifying the calculation to ,
ensuring the duration remains positive and accurate.

Signed-off-by: Anju Pathak <[email protected]>
anjupathak03 and others added 5 commits February 6, 2026 15:53
…ting without persisted session metadata

The problem:
Mock routing during recording depended on `session_name` stored inside mock metadata.
That created coupling between persisted mock content and runtime session state.
As we moved to session-driven replay/loading, we needed session segregation in recording
without relying on metadata embedded in saved mocks.

What this introduces:
A lightweight stream envelope (`MockFrame`) that carries:
- the recorded mock payload
- the active session name at stream time

Why this helps:
- Session context stays runtime-only, not persisted in mock schema.
- Recorder can route writes correctly:
  - run root when no session is active
  - session-scoped path when `/start-session` is active
- Replay/session behavior stays consistent with session lifecycle.
- Removes need for parser-level session tagging solely for routing.

Key implementation idea:
Session name is attached at the outgoing stream boundary and consumed by recorder routing logic,
instead of being derived from persisted mock metadata.

Result:
- Cleaner separation of concerns:
  - mock data = protocol content
  - routing context = runtime session envelope
- Session segregation still works
- Root fallback still works
- No `session_name` persistence requirement for this flow

Signed-off-by: Anju Pathak <[email protected]%>
Signed-off-by: Anju Pathak <[email protected]%>
…y pipeline internals

The MCP workflow is simplified to an orchestration-first model:
`keploy_manager` now acts as a coordinator that returns the execution sequence,
while specialized tools handle prompt generation, mock record, and mock test.

This change removes the previous in-server “smart pipeline generator” and other
manual orchestration logic that had become heavy, hard to maintain, and tightly
coupled to environment detection. The new model keeps business logic minimal on
the server and pushes repository-aware edits to the client LLM via prompt tools.

What changed:
- Converted manager flow to orchestration-only guidance.
- Removed legacy action-based routing and related manager schema fields.
- Added prompt tooling backed by TOML templates for:
  - test integration (`start-session` instrumentation prompt),
  - CI pipeline creation prompt.
- Removed old pipeline/template/list-mocks implementation and related types.
- Tightened tool-selection guidance so manager is default entrypoint.
- Kept replay path behavior optional so downstream replay can resolve latest run.
- Simplified agent env export to only `KEPLOY_AGENT_URI`.

Why:
- Reduce MCP server complexity and duplicated decision logic.
- Make behavior deterministic and easier to evolve through prompt templates.
- Avoid stale platform/language heuristics inside server code.
- Keep orchestration explicit and easier for clients to reason about.

Signed-off-by: Anju Pathak <[email protected]%>
runner, ok := recordSvc.(mockrecord.RecordRunner)
if !ok {
utils.LogError(mcpLogger, nil, "service doesn't satisfy record runner interface")
return nil
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: Silent failure - returns nil instead of an error when type assertion fails.

When recordSvc doesn't satisfy the mockrecord.RecordRunner interface, this logs an error but returns nil, causing the MCP server to silently fail without informing the caller. Consider returning an actual error:

Suggested change
return nil
return fmt.Errorf("service doesn't satisfy record runner interface")

replayRuntime, ok := replaySvc.(mockreplay.Runtime)
if !ok {
utils.LogError(mcpLogger, nil, "service doesn't satisfy replay runtime interface")
return nil
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: Silent failure - returns nil instead of an error when type assertion fails.

Same issue as line 235. When replaySvc doesn't satisfy the mockreplay.Runtime interface, this silently fails. Consider returning an actual error:

Suggested change
return nil
return fmt.Errorf("service doesn't satisfy replay runtime interface")

@kilo-code-bot
Copy link
Contributor

kilo-code-bot bot commented Feb 10, 2026

Code Review Summary

Status: 29 Issues Found | Recommendation: Address before merge

Overview

Severity Count
CRITICAL 2
WARNING 12
SUGGESTION 15
Issue Details (click to expand)

CRITICAL

File Line Issue
cli/mcp.go 230 Silent failure - returns nil instead of error when service doesn't satisfy interface
cli/mcp.go 242 Silent failure - returns nil instead of error when service doesn't satisfy interface

WARNING

File Line Issue
cli/mcp.go 208 os.Stdout redirection to /dev/null happens after capturing original stdout
pkg/platform/http/agent.go 612 Error at line 591 is now always sent to appErrCh
utils/ctx.go 56 NewMCPCtx creates context that only listens to OS signals, may not integrate with Stop/ExecCancel
pkg/service/replay/replay.go 775 SQLDelay multiplied by time.Second - verify this is intentional
cli/mcp.go 92, 192, 207 File handle may be writable as result of data flow
cli/sandbox.go 132 Consider using Debug level instead of Warn
pkg/service/record/record.go 484 Consider using Debug level instead of Warn

SUGGESTION

File Line Issue
utils/signal_others.go 73 Error log missing actionable next step
pkg/service/sandbox/cloud_client.go 155 Error message missing actionable next step
cli/sandbox.go 74, 97 Error log missing actionable next step
pkg/agent/routes/record.go 76 Error log missing actionable next step
pkg/mcp/tools.go 247, 456 Error log missing actionable next step
pkg/agent/proxy/util/util.go N/A IP4StrToUint32 and IP6StrToUint32 functions added but not used
Files Reviewed (35 files)
  • Mocker.README.md - Documentation (no issues)
  • cli/mcp.go - 5 issues
  • cli/sandbox.go - 3 issues
  • cli/sandbox_test.go - No issues
  • config/config.go - No issues
  • config/default.go - No issues
  • pkg/agent/proxy/util/util.go - 1 issue
  • pkg/agent/routes/record.go - 1 issue
  • pkg/mcp/tools.go - 2 issues
  • pkg/models/mock.go - No issues
  • pkg/models/record.go - No issues
  • pkg/models/replay.go - No issues
  • pkg/models/sandbox.go - No issues
  • pkg/platform/http/agent.go - 1 issue
  • pkg/platform/yaml/mockdb/db.go - No issues
  • pkg/service/record/record.go - 2 issues
  • pkg/service/record/service.go - No issues
  • pkg/service/replay/mock.go - No issues
  • pkg/service/replay/replay.go - 1 issue
  • pkg/service/replay/runtime.go - No issues
  • pkg/service/replay/service.go - No issues
  • pkg/service/sandbox/cloud_client.go - 1 issue
  • pkg/service/sandbox/sandbox.go - No issues
  • pkg/service/sandbox/sandbox_test.go - No issues
  • pkg/service/sandbox/service.go - No issues
  • pkg/service/mockrecord/record.go - No issues
  • pkg/service/mockrecord/metadata.go - No issues
  • pkg/service/mockrecord/service.go - No issues
  • pkg/service/mockreplay/replay.go - No issues
  • utils/ctx.go - 1 issue
  • utils/log/logger.go - No issues
  • utils/mcp.go - No issues
  • utils/signal_others.go - 1 issue
  • utils/signal_windows.go - No issues
  • utils/utils.go - No issues

Fix these issues in Kilo Cloud

anjupathak03 and others added 4 commits February 11, 2026 13:54
… protocols only

Replace timestamp-based mock run directories with sequential mock-set naming,
and align replay resolution/docs with the new convention.

What changed:
- mock record now writes to `mock-set-<n>` under the provided base path.
- explicit `mock-set-*` paths are respected as-is; otherwise next set id is computed.
- mock replay latest-path resolution now scans only `mock-set-*` directories.
- removed legacy `run-*` auto-resolution fallback.
- updated CLI/MCP examples and schema descriptions to reference `mock-set-*`.
- simplified mockrecord metadata collector to protocol aggregation only.
- removed unused endpoint/service-name/timestamp extraction logic and dead helpers.

Why:
- deterministic, readable mock set naming (`mock-set-0/1/2/...`).
- cleaner replay semantics (single naming scheme, no dual-mode resolution).
- reduced metadata complexity to what is actively consumed by record summaries/API.

Signed-off-by: Anju Pathak <[email protected]%>
Added comprehensive documentation for Keploy's mock recording and replay functionality, including quick start, local setup, cloud integration, CI/CD pipeline integration, and important notes.

Signed-off-by: Gourav kumar <[email protected]>
Switch mock session routing from set-name semantics to explicit file-path semantics.

- Treat `/agent/hooks/start-session` `name` as full mock file path (including filename).
- Record mode: create/truncate the target file on session start and write outgoing mocks directly to that path.
- Replay mode: remove startup/root preloading and load mocks only from the file path provided via start-session.
- Add mockdb path-based helpers for direct file operations:
  - `InsertMockToPath(...)`
  - `LoadMocksFromPath(...)`
- Keep fallback behavior when no start-session is received: existing default mockDB write path flow remains.

Signed-off-by: Anju <[email protected]%>
… tool

- add `keploy_prompt_test_command` tool to return raw prompt text for deriving app test commands
- migrate prompt templates from single `prompts.toml` to `pkg/mcp/prompts/*.toml`
  - `app_test_command.toml`
  - `test_integration.toml`
  - `pipeline_creation.toml`
- update prompt loading to read embedded prompt files directly
- wire `test_command` variable through integration and pipeline prompt builders
- remove legacy `pkg/mcp/prompts.toml`
- update manager orchestration text to include command-prompt-first flow
- clarify tool/server descriptions for unresolved command handling:
  pass empty command through; server-side elicitation resolves it in execution tools
- refresh MCP tool registration/types for the new prompt tool

Signed-off-by: Anju <[email protected]%>
anjupathak03 and others added 4 commits February 13, 2026 00:00
…rchestration flow

  This commit addresses several critical issues in the MCP agent workflow regarding file
permissions, path resolution, and execution continuity.

  **1. Fix Permission Denied (`EACCES`) on Mock Files:**
  - Introduced `utils.SetOwnershipToSudoUser` helper to immediately transfer ownership of
newly created files/directories to the `SUDO_USER` (via `SUDO_UID`/`SUDO_GID`).
  - Applied this fix in:
    - `pkg/service/agent/agent.go`: For `start-session` mock file creation.
    - `pkg/platform/yaml/mockdb/db.go`: For recording new mocks.
    - `pkg/platform/yaml/yaml.go`: For general YAML file creation.
  - **Rationale**: Keploy runs as root (required for eBPF). Unlike standard CLI commands which
perform a bulk permission fix on exit, the Agent is long-running and creates files dynamically
These files were being created as `root`, preventing users/IDEs from deleting or modifying
them while the agent was running. This change ensures files are immediately owned by the user
upon creation.

  **2. Fix Path Resolution and Extensions:**
  - **Agent**: Removed logic in `StartMockSession` that forced paths to be relative to
`config.Path`. Now respects the caller's path relative to the project root, fixing the issue
where mocks were incorrectly nested inside `keploy/`.
  - **Prompts (`test_integration.toml`)**:
    - Updated instructions to explicitly add the `.yml` extension to `StartKeploySession`
calls (e.g., `kMocks/TestName.yml`), ensuring consistent file naming.
    - Corrected the `start-session` endpoint URL in generated pseudocode (removed incorrect
`/agent` prefix; now `/hooks/start-session`).
    - Clarified that `<SCOPE_PATH>` must be relative to the project root.

  **3. Enforce Continuous Orchestration:**
  - Updated `pkg/mcp/server.go` and `pkg/mcp/manager.go` to strictly enforce the full 6-step
workflow.
  - Directives now explicitly instruct the Client LLM to "EXECUTE ALL STEPS IN ONE GO" and
"IMMEDIATELY" proceed to Replay and Pipeline creation after Recording, preventing the
assistant from pausing or asking for confirmation mid-workflow.

◇ Gemini 3 Pro (Previe

Signed-off-by: Anju <[email protected]>
Updated README to reflect changes in commands and mock storage structure.

Signed-off-by: Gourav kumar <[email protected]>
Signed-off-by: Gourav kumar <[email protected]>
- Introduce sandbox-focused workflow:
  - `keploy sandbox record`
  - `keploy sandbox replay`
- Keep legacy `keploy mock download/upload` behavior unchanged.
- Replace start-session scoping with sandbox scope API:
  - `POST /agent/sandbox/scope`
  - payload: `{location, name}`
- Use sandbox file naming/location model:
  - `<location>/<name>.sb.yaml`
  - default fallback via helper (`./keploy.sb.yaml` when unset)
- In record mode:
  - on scope request, create/overwrite target sandbox file
  - route outgoing writes to the active scoped file path
- In replay mode:
  - load startup sandbox file if present
  - if missing, continue and wait for `/sandbox/scope`
  - on scope request, load scoped sandbox and replace in-memory mocks
- Update MCP tool/prompt text and pipeline prompt to sandbox terminology and scope endpoint.
- Add `.gitignore` entries for nested sandbox files:
  - `**/*.sb.yaml`
  - `**/*.sb.yml`
  with explicit error logging.
- Add safety checks in legacy replay upload/download path to skip sandbox files.

Signed-off-by: Anju <[email protected]>

logFile, err := os.Create(logFilePath)
if err != nil {
logger.Error("failed to create log file for docker-compose output", zap.Error(err))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: Error log missing actionable next step

Per the custom instructions, error logs should provide a logical next step for the user. This error just says "failed to create log file" but doesn't tell the user what to do about it.

Suggested change
logger.Error("failed to create log file for docker-compose output", zap.Error(err))
logger.Error("failed to create log file for docker-compose output; check write permissions in temp directory or set a custom temp path", zap.Error(err), zap.String("path", logFilePath))

func (c *CloudClient) addAuthHeader(req *http.Request) error {
token := strings.TrimSpace(c.jwtToken)
if token == "" {
return fmt.Errorf("missing jwt token")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: Error message missing actionable next step

Per the custom instructions, error messages should provide a logical next step. This error just says "missing jwt token" but doesn't tell the user how to fix it.

Suggested change
return fmt.Errorf("missing jwt token")
return fmt.Errorf("missing jwt token; please run 'keploy login' to authenticate or set the KEPLOY_API_KEY environment variable")

}
tagInput = strings.TrimSpace(tagInput)
if tagInput == "" {
logger.Error("--tag flag is mandatory for sandbox record (format: <tag>, e.g. v1.0.0)")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: Error log missing actionable next step

The error message tells the user what's wrong but doesn't provide a clear next step. Consider adding guidance like:

Suggested change
logger.Error("--tag flag is mandatory for sandbox record (format: <tag>, e.g. v1.0.0)")
logger.Error("--tag flag is mandatory for sandbox record (format: <tag>, e.g. v1.0.0). Please re-run with --tag <version>")

fmt.Fprintln(cmd.OutOrStdout(), output)
}
if result.AppExitCode != 0 {
logger.Warn("sandbox record command exited with non-zero code",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: Consider using Debug level instead of Warn

Per the custom instructions, warnings should not be added. A non-zero exit code from the user's command is informational rather than a warning about Keploy itself. Consider using logger.Debug or logger.Info instead:

Suggested change
logger.Warn("sandbox record command exited with non-zero code",
logger.Info("sandbox record command exited with non-zero code",

}

if err := a.svc.StartSandboxScope(r.Context(), req.Location, req.Name); err != nil {
a.logger.Error("failed to start sandbox scope", zap.Error(err))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: Error log missing actionable next step

The error log should provide guidance on what the user can do to resolve the issue. Consider adding context about common causes:

Suggested change
a.logger.Error("failed to start sandbox scope", zap.Error(err))
a.logger.Error("failed to start sandbox scope. Ensure the location path exists and is writable", zap.Error(err))

Name: name,
})
if err != nil {
s.logger.Error("Mock recording failed", zap.Error(err))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: Error log missing actionable next step

The error log should provide guidance on what the user can do to resolve the issue. Consider adding troubleshooting hints:

Suggested change
s.logger.Error("Mock recording failed", zap.Error(err))
s.logger.Error("Mock recording failed. Check that the command is valid and the application can start", zap.Error(err))

FallBackOnMiss: in.FallBackOnMiss,
})
if err != nil {
s.logger.Error("Mock replay failed", zap.Error(err))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: Error log missing actionable next step

The error log should provide guidance on what the user can do to resolve the issue. Consider adding troubleshooting hints:

Suggested change
s.logger.Error("Mock replay failed", zap.Error(err))
s.logger.Error("Mock replay failed. Verify sandbox files exist at the specified path and the command is valid", zap.Error(err))

}

if opts.IgnoreAppError && (appErr.AppErrorType == models.ErrCommandError || appErr.AppErrorType == models.ErrUnExpected) {
r.logger.Warn(stopReason, zap.Error(appErr))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: Consider using Debug level instead of Warn

Per the custom instructions, warnings should not be added. This warning logs when IgnoreAppError is true and the app exits with an error - which is an expected/handled case. Consider using Debug level instead since this is informational for developers rather than a warning condition.

Suggested change
r.logger.Warn(stopReason, zap.Error(appErr))
r.logger.Debug(stopReason, zap.Error(appErr))


recordSvc, err := serviceFactory.GetService(ctx, "record")
if err != nil {
utils.LogError(logger, err, "failed to get record service")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: Error log missing actionable next step

The error message "failed to get record service" doesn't guide the user on what to do next. Consider adding a suggestion like "ensure the record service is properly configured" or "check if the required dependencies are installed".


runner, ok := recordSvc.(mockrecord.RecordRunner)
if !ok {
utils.LogError(logger, nil, "service doesn't satisfy record runner interface")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: Error log missing actionable next step

The error message "service doesn't satisfy record runner interface" is technical and doesn't help the user. Consider adding context like "this may indicate a version mismatch - try updating keploy to the latest version".

DNSPort: cfg.DNSPort,
})
if err != nil {
utils.LogError(logger, err, "failed to record mocks")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: Error log missing actionable next step

The error message "failed to record mocks" doesn't provide guidance. Consider adding suggestions like "check if the application is running correctly" or "verify the proxy configuration".

// Always overwrite the sandbox ref in keploy.yml during mock recording.
cfg.Sandbox.Ref = ref
if err := updateSandboxRefInConfig(cfg, ref); err != nil {
utils.LogError(logger, err, "failed to update sandbox ref in config")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: Error log missing actionable next step

The error message "failed to update sandbox ref in config" doesn't guide the user. Consider adding suggestions like "check file permissions for keploy.yml" or "ensure the config directory is writable".

// Step 3: Proceed with normal mock replay.
replaySvc, err := serviceFactory.GetService(ctx, "test")
if err != nil {
utils.LogError(logger, err, "failed to get replay service")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: Error log missing actionable next step

The error message "failed to get replay service" doesn't guide the user on what to do next. Consider adding a suggestion like "ensure the replay service is properly configured" or "check if the required dependencies are installed".


runtime, ok := replaySvc.(mockreplay.Runtime)
if !ok {
utils.LogError(logger, nil, "service doesn't satisfy replay runtime interface")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: Error log missing actionable next step

The error message "service doesn't satisfy replay runtime interface" is technical and doesn't help the user. Consider adding context like "this may indicate a version mismatch - try updating keploy to the latest version".

DNSPort: cfg.DNSPort,
})
if err != nil {
utils.LogError(logger, err, "failed to replay mocks")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: Error log missing actionable next step

The error message "failed to replay mocks" doesn't provide guidance. Consider adding suggestions like "check if the mock files exist at the specified location" or "verify the sandbox file format is correct".

defer resp.Body.Close()

if resp.StatusCode == http.StatusNotFound {
c.logger.Info("sandbox manifest not found in cloud", zap.String("ref", ref))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: Consider using Debug level instead of Info

This log indicates a 404 response which is an expected case (manifest not found). Since this is normal behavior when the ref doesn't exist yet, consider using Debug level instead of Info to reduce noise for users.


mockFileContent, err := osReadFile224(localMockPath)
if err != nil {
m.logger.Error("Failed to read mock file for mock upload", zap.String("path", localMockPath), zap.Error(err))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: Error log missing actionable next step

The error message "Failed to read mock file for mock upload" doesn't provide guidance on what the user should do next. Consider adding a suggestion like "Ensure the mock file exists at the specified path and has proper read permissions."


mockFileContent, err := osReadFile224(localMockPath)
if err != nil {
m.logger.Error("Failed to read mock file for mock upload", zap.String("path", localMockPath), zap.Error(err))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: Error log missing actionable next step

The error message tells the user what failed but doesn't provide guidance on how to resolve it. Consider adding a next step like:

Suggested change
m.logger.Error("Failed to read mock file for mock upload", zap.String("path", localMockPath), zap.Error(err))
m.logger.Error("Failed to read mock file for mock upload. Verify the file exists and has read permissions.", zap.String("path", localMockPath), zap.Error(err))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants