Skip to content

feat: Implement per-session prompt functionality #459

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 15 commits into
base: main
Choose a base branch
from

Conversation

sebastianripari
Copy link

@sebastianripari sebastianripari commented Jun 28, 2025

Description

This PR adds support for session-specific prompts in the MCP server, allowing different prompts to be available per client session. This mirrors the existing session-specific tools functionality and enables dynamic prompt customization based on session context.

Type of Change

  • New feature (non-breaking change that adds functionality)
  • MCP spec compatibility implementation
  • Tests only (no functional changes)

Changes Made

Core Functionality

  1. Enhanced sseSession struct: Added prompts sync.Map field to store session-specific prompts
  2. Implemented SessionWithPrompts interface: Added methods for managing session prompts
  3. Updated handleGetPrompt: Modified to check session-specific prompts first, then fall back to global prompts
  4. Updated handleListPrompts: Modified to merge session-specific prompts with global prompts in the list

Server Methods

  • Added AddSessionPrompts(sessionID string, prompts ...ServerPrompt) error
  • Added AddSessionPrompt(sessionID string, prompt mcp.Prompt, handler PromptHandlerFunc) error
  • Added DeleteSessionPrompts(sessionID string, names ...string) error

Testing

  • Added comprehensive test suite for session-specific prompts functionality
  • Tests cover integration, uninitialized sessions, prompt overriding, and concurrent access
  • All tests pass and maintain backward compatibility

Checklist

  • My code follows the code style of this project
  • I have performed a self-review of my own code
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the documentation accordingly

MCP Spec Compliance

  • This PR implements a feature defined in the MCP specification
  • Link to relevant spec section: Prompts
  • Implementation follows the specification exactly

Additional Information

This implementation follows the same pattern as the existing session-specific tools functionality, ensuring consistency across the codebase. The feature allows for:

  • Session-specific prompt overrides of global prompts
  • Dynamic prompt management per session
  • Proper notification handling for prompt list changes
  • Thread-safe concurrent access to session prompts

The implementation maintains full backward compatibility and doesn't affect existing global prompt functionality.

Summary by CodeRabbit

  • New Features

    • Added support for session-specific prompt customization, allowing prompts to be defined and managed on a per-session basis.
    • Session-specific prompts can override or supplement global prompts for individual client sessions.
  • Documentation

    • Updated documentation to mention support for per-session prompt customization in session management features.
  • Tests

    • Added comprehensive tests to verify session-specific prompt management, including prompt addition, retrieval, notification behavior, and thread safety.

Copy link
Contributor

coderabbitai bot commented Jun 28, 2025

Walkthrough

This change introduces per-session prompt customization to the session management system. It adds a new interface for session-specific prompts, updates the server to merge and prioritize session prompts over global ones, and implements methods for adding, retrieving, and testing session prompts. Documentation and error handling are also updated accordingly.

Changes

Files / Areas Summary of Changes
README.md Updated documentation to mention support for per-session prompt customization in the session management feature list.
server/errors.go Added new error variable ErrSessionDoesNotSupportPrompts for sessions that do not support per-session prompts.
server/server.go Modified prompt listing and retrieval methods to check for and merge session-specific prompts, allowing session prompts to override or supplement global prompts.
server/session.go Introduced SessionWithPrompts interface and added AddSessionPrompts and AddSessionPrompt methods for managing session-specific prompts, including notification logic.
server/session_test.go Added sessionTestClientWithPrompts test client, new tests for prompt management in sessions, and updated interface satisfaction checks.
server/sse.go Extended sseSession with a prompts field and added methods for getting and setting session-specific prompts, mirroring session tool management.
server/sse_test.go Added a new subtest to verify correct and thread-safe prompt management in SSE sessions, including concurrency checks.

Possibly related PRs

  • mark3labs/mcp-go#232: Extends session-specific customization by adding prompt management to sseSession alongside existing tool management, directly building on the same struct and pattern introduced in the retrieved PR for session tools.

Suggested labels

area: sdk

Suggested reviewers

  • ezynda3
  • pottekkat

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (1.64.8)

Error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2
Failed executing command with error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 50f4681 and 9339179.

📒 Files selected for processing (1)
  • server/sse_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • server/sse_test.go
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (4)
README.md (1)

550-550: LGTM: Documentation accurately reflects new capability.

The addition of "per-session prompt customization" appropriately documents the new feature alongside existing tool customization capabilities.

Consider fixing the markdown list style for consistency:

-- Provide per-session prompt customization
+* Provide per-session prompt customization
server/server.go (1)

849-849: Fix typo in comment.

The comment mentions "tools" instead of "prompts".

-				// Then override with session-specific tools
+				// Then override with session-specific prompts
server/session_test.go (2)

486-486: Fix copy-paste error in comment.

-	// Add session-specific tool using the new helper method
+	// Add session-specific prompt using the new helper method

642-642: Fix copy-paste errors in comments.

Multiple comments incorrectly refer to "tools" instead of "prompts".

-	// Add session-specific tools to the uninitialized session
+	// Add session-specific prompts to the uninitialized session
-	// Now verify that subsequent tool additions will send notifications
+	// Now verify that subsequent prompt additions will send notifications
-	// Verify both tools are available
+	// Verify both prompts are available

Also applies to: 669-669, 690-690

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1eddde7 and 50f4681.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (8)
  • README.md (1 hunks)
  • go.mod (1 hunks)
  • server/errors.go (1 hunks)
  • server/server.go (2 hunks)
  • server/session.go (2 hunks)
  • server/session_test.go (6 hunks)
  • server/sse.go (3 hunks)
  • server/sse_test.go (1 hunks)
🧰 Additional context used
🧠 Learnings (6)
📓 Common learnings
Learnt from: lariel-fernandes
PR: mark3labs/mcp-go#428
File: www/docs/pages/servers/prompts.mdx:218-234
Timestamp: 2025-06-20T20:39:51.870Z
Learning: In the mcp-go library, the GetPromptParams.Arguments field is of type map[string]string, not map[string]interface{}, so direct string access without type assertions is safe and correct.
Learnt from: leavez
PR: mark3labs/mcp-go#114
File: client/transport/sse.go:137-179
Timestamp: 2025-04-06T10:07:06.685Z
Learning: The SSE client implementation in the MCP-Go project uses a 30-second timeout for reading SSE events to match the behavior of the original implementation before the transport layer refactoring.
server/sse_test.go (2)
Learnt from: octo
PR: mark3labs/mcp-go#149
File: mcptest/mcptest.go:0-0
Timestamp: 2025-04-21T21:26:32.945Z
Learning: In the mcptest package, prefer returning errors from helper functions rather than calling t.Fatalf() directly, giving callers flexibility in how to handle errors.
Learnt from: lariel-fernandes
PR: mark3labs/mcp-go#428
File: www/docs/pages/servers/prompts.mdx:218-234
Timestamp: 2025-06-20T20:39:51.870Z
Learning: In the mcp-go library, the GetPromptParams.Arguments field is of type map[string]string, not map[string]interface{}, so direct string access without type assertions is safe and correct.
server/sse.go (1)
Learnt from: lariel-fernandes
PR: mark3labs/mcp-go#428
File: www/docs/pages/servers/prompts.mdx:218-234
Timestamp: 2025-06-20T20:39:51.870Z
Learning: In the mcp-go library, the GetPromptParams.Arguments field is of type map[string]string, not map[string]interface{}, so direct string access without type assertions is safe and correct.
server/server.go (1)
Learnt from: lariel-fernandes
PR: mark3labs/mcp-go#428
File: www/docs/pages/servers/prompts.mdx:218-234
Timestamp: 2025-06-20T20:39:51.870Z
Learning: In the mcp-go library, the GetPromptParams.Arguments field is of type map[string]string, not map[string]interface{}, so direct string access without type assertions is safe and correct.
server/session.go (1)
Learnt from: lariel-fernandes
PR: mark3labs/mcp-go#428
File: www/docs/pages/servers/prompts.mdx:218-234
Timestamp: 2025-06-20T20:39:51.870Z
Learning: In the mcp-go library, the GetPromptParams.Arguments field is of type map[string]string, not map[string]interface{}, so direct string access without type assertions is safe and correct.
server/session_test.go (4)
Learnt from: lariel-fernandes
PR: mark3labs/mcp-go#428
File: www/docs/pages/servers/prompts.mdx:218-234
Timestamp: 2025-06-20T20:39:51.870Z
Learning: In the mcp-go library, the GetPromptParams.Arguments field is of type map[string]string, not map[string]interface{}, so direct string access without type assertions is safe and correct.
Learnt from: octo
PR: mark3labs/mcp-go#149
File: mcptest/mcptest.go:0-0
Timestamp: 2025-04-21T21:26:32.945Z
Learning: In the mcptest package, prefer returning errors from helper functions rather than calling t.Fatalf() directly, giving callers flexibility in how to handle errors.
Learnt from: floatingIce91
PR: mark3labs/mcp-go#401
File: server/server.go:1082-1092
Timestamp: 2025-06-23T11:10:42.948Z
Learning: In Go MCP server, ServerTool.Tool field is only used for tool listing and indexing, not for tool execution or middleware. During handleToolCall, only the Handler field is used, so dynamic tools don't need the Tool field populated.
Learnt from: xinwo
PR: mark3labs/mcp-go#35
File: mcp/tools.go:107-137
Timestamp: 2025-03-04T06:59:43.882Z
Learning: Tool responses from the MCP server shouldn't contain RawInputSchema, which is why the UnmarshalJSON method for the Tool struct is implemented to handle only the structured InputSchema format.
🧬 Code Graph Analysis (4)
server/sse_test.go (7)
server/hooks.go (1)
  • Hooks (94-121)
server/session.go (1)
  • ClientSession (11-20)
server/server.go (1)
  • ServerPrompt (56-59)
server/sse.go (1)
  • NewTestServer (302-308)
mcp/prompts.go (5)
  • Prompt (45-53)
  • GetPromptResult (34-39)
  • PromptMessage (86-89)
  • Role (75-75)
  • RoleUser (78-78)
mcp/utils.go (1)
  • NewGetPromptResult (407-415)
mcp/types.go (3)
  • Content (827-829)
  • TextContent (833-838)
  • TextContent (840-840)
server/sse.go (1)
server/server.go (1)
  • ServerPrompt (56-59)
server/server.go (2)
server/session.go (2)
  • ClientSessionFromContext (79-84)
  • SessionWithPrompts (42-48)
mcp/prompts.go (1)
  • Prompt (45-53)
server/session.go (4)
server/server.go (3)
  • ServerPrompt (56-59)
  • MCPServer (138-163)
  • PromptHandlerFunc (38-38)
server/errors.go (2)
  • ErrSessionNotFound (16-16)
  • ErrSessionDoesNotSupportPrompts (20-20)
mcp/prompts.go (1)
  • Prompt (45-53)
server/hooks.go (1)
  • Hooks (94-121)
🪛 markdownlint-cli2 (0.17.2)
README.md

550-550: Unordered list style
Expected: asterisk; Actual: dash

(MD004, ul-style)

🔇 Additional comments (12)
go.mod (1)

12-12: LGTM: Indirect dependency addition is appropriate.

The addition of golang.org/x/sys as an indirect dependency is expected to support the new session-specific prompt management features that use concurrency primitives.

server/errors.go (1)

20-20: LGTM: Error definition follows established patterns.

The new error variable ErrSessionDoesNotSupportPrompts is correctly positioned with other session-related errors and follows the established naming convention, providing consistency with the existing ErrSessionDoesNotSupportTools error.

server/sse.go (3)

32-32: LGTM: Consistent field addition for prompt storage.

The prompts sync.Map field follows the same pattern as the existing tools sync.Map, providing thread-safe storage for session-specific prompts.


78-87: LGTM: GetSessionPrompts implementation follows established pattern.

The method correctly iterates over the sync.Map with proper type assertion and error handling, mirroring the implementation of GetSessionTools.


100-108: LGTM: SetSessionPrompts implementation is thread-safe and correct.

The method properly clears existing prompts before setting new ones, following the same pattern as SetSessionTools and ensuring thread-safe operations with sync.Map.

server/server.go (1)

894-915: LGTM! Session-specific prompt retrieval is well-implemented.

The implementation correctly prioritizes session-specific prompts over global ones and avoids variable shadowing issues.

server/session.go (2)

390-441: Well-implemented session prompt management.

The implementation correctly follows the established pattern from AddSessionTools, including proper error handling, concurrent safety with map copying, and non-blocking notification handling.


443-445: LGTM! Consistent wrapper implementation.

The wrapper method follows the same pattern as AddSessionTool.

server/session_test.go (4)

140-140: Good comment correction.

Thanks for fixing the comment to accurately describe the type.


175-230: Excellent thread-safe test client implementation.

The implementation correctly uses mutex protection and defensive copying to ensure thread safety, following the same robust pattern as sessionTestClientWithTools.


396-429: Well-structured test for session prompt addition.

The test comprehensively verifies prompt addition and notification behavior, following the established pattern from tool tests.


845-915: Comprehensive test for session prompt retrieval.

The test thoroughly validates that session-specific prompts correctly override global prompts, with proper type assertion and content validation.

Comment on lines +42 to +48
type SessionWithPrompts interface {
ClientSession
// GetPrompts returns the prompts specific to this session, if any
GetSessionPrompts() map[string]ServerPrompt
// SetPrompts sets prompts specific to this session
SetSessionPrompts(prompts map[string]ServerPrompt)
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Document thread-safety requirements for consistency.

The SessionWithTools interface above documents thread-safety requirements in its method comments, but SessionWithPrompts does not. For consistency and to ensure proper implementation, please add similar documentation.

 type SessionWithPrompts interface {
 	ClientSession
-	// GetPrompts returns the prompts specific to this session, if any
+	// GetSessionPrompts returns the prompts specific to this session, if any
+	// This method must be thread-safe for concurrent access
 	GetSessionPrompts() map[string]ServerPrompt
-	// SetPrompts sets prompts specific to this session
+	// SetSessionPrompts sets prompts specific to this session
+	// This method must be thread-safe for concurrent access
 	SetSessionPrompts(prompts map[string]ServerPrompt)
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
type SessionWithPrompts interface {
ClientSession
// GetPrompts returns the prompts specific to this session, if any
GetSessionPrompts() map[string]ServerPrompt
// SetPrompts sets prompts specific to this session
SetSessionPrompts(prompts map[string]ServerPrompt)
}
type SessionWithPrompts interface {
ClientSession
// GetSessionPrompts returns the prompts specific to this session, if any
// This method must be thread-safe for concurrent access
GetSessionPrompts() map[string]ServerPrompt
// SetSessionPrompts sets prompts specific to this session
// This method must be thread-safe for concurrent access
SetSessionPrompts(prompts map[string]ServerPrompt)
}
🤖 Prompt for AI Agents
In server/session.go around lines 42 to 48, the SessionWithPrompts interface
lacks thread-safety documentation unlike the SessionWithTools interface. Add
comments to the GetSessionPrompts and SetSessionPrompts methods specifying their
thread-safety requirements, indicating whether they must be safe for concurrent
use or require external synchronization, to maintain consistency and guide
proper implementation.

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.

1 participant