feat: autocompletion for prompt args and resource template URI args
Description
Fixes #417
- Handle the method
compeltion/complete - Add the
Contextfield to theCompleteRequest - Allow implementations to configure autocomplete handlers for prompt argumens and arguments of resource template URIs
Example usage:
s := server.NewMCPServer(...)
// Usage with Prompt
mcpServer.AddPrompt(
mcp.NewPrompt(
"Tell me a {adjective} joke about {subject}",
mcp.WithArgument(
"adjective",
mcp.ArgumentCompletion(func(ctx context.Context, request mcp.CompleteRequest) (*mcp.CompleteResult, error) {
input := request.Params.Argument.Value
// TODO: Check dictionary for adjectives, fuzzy match against input, return suggestions
}),
),
),
promptHandler,
)
// Usage with ResourceTemplate
s.AddResourceTemplate(
mcp.NewResourceTemplate(
"postgresql://{userName}@host:5432/{databaseName}", // URI template
"Database", // Resource name
mcp.WithTemplateArgumentCompletion(
"databaseName",
func(_ context.Context, request mcp.CompleteRequest) (*mcp.CompleteResult, error) {
input := request.Params.Argument.Value
user := request.Params.Context.Arguments["user"]
// TODO: check available databases for user, fuzzy match against input, return matches
}
),
),
resourceTemplateHandler,
)
Type of Change
- [x] New feature (non-breaking change that adds functionality)
- [x] MCP spec compatibility implementation
Checklist
- [x] My code follows the code style of this project
- [x] I have performed a self-review of my own code
- [x] I have added tests that prove my fix is effective or that my feature works
- [x] I have updated the documentation accordingly
MCP Spec Compliance
- [x] This PR implements a feature defined in the MCP specification
- [x] Link to relevant spec section: Completion
- [x] Implementation follows the specification exactly
Additional Information
- It was necessary to declare
CompletionHandlerFuncin themcppackage instead of theserverpackage to avoid a circular import. Any suggestions on how to solve this with a cleaner approach are welcome.
Summary by CodeRabbit
Summary by CodeRabbit
- New Features
- Added support for autocompletion of URI and prompt arguments, enabling dynamic suggestion capabilities.
- Introduced new server capability for completions, automatically registered when relevant handlers are present.
- Added hooks for handling actions before and after completion requests.
- Improvements
- Enhanced type safety for resource and prompt references.
- Improved error handling and response clarity for completion requests.
- Documentation
- Added example demonstrating basic argument completion for prompts with a dictionary-based handler.
- Tests
- Added tests verifying completion request handling, including success, no results, and error scenarios.
Walkthrough
This change introduces structured support for autocompletion of prompt and resource template arguments in the MCP server. It adds completion handler functions, new server capabilities, completion-specific hooks, and request handling for the new "completion/complete" method. Type safety and contextual information for completions are also improved.
Changes
| Files / Paths | Change Summary |
|---|---|
| mcp/prompts.go, mcp/resources.go | Added CompletionHandler field and functional options to associate completion handlers with prompt arguments and URI template arguments. |
| mcp/types.go | Introduced CompletionHandlerFunc, extended URITemplate with argument completion handlers, added completion method constant, improved reference typing with RefType, and added context to completion parameters. |
| mcp/utils.go | Added ParseCompletionReference to parse and validate completion request references into typed prompt or resource references. |
| server/hooks.go | Added before/after completion hooks, their registration methods, and invocation logic in the server hook system. |
| server/request_handler.go | Added handling for the new "completion/complete" method in the server's message handler with error handling and hooks. |
| server/server.go | Added completions capability flag, implicit registration logic when adding resource templates or prompts, inclusion of completions in initialization response, and a handler method for completion requests. |
| www/docs/pages/servers/prompts.mdx | Added example for basic argument completion demonstrating dictionary-based completion handler and prompt registration. |
| server/server_test.go | Added tests for completion capability registration and completion request handling including success and error cases. |
Assessment against linked issues
| Objective | Addressed | Explanation |
|---|---|---|
Add Context field to CompletionRequest and implement context handling in completion logic (#417) |
✅ |
Assessment against linked issues: Out-of-scope changes
No out-of-scope changes were identified. All changes align with the objectives of adding context-aware completion support and related features.
Suggested reviewers
- robert-jackson-glean
- dugenkui03
[!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 bf34fb21bdbb72c93550641d5045808d03905957 and c16e99f6b9164c58123acb7b0fb95b2a02ac1bc6.
📒 Files selected for processing (2)
server/server.go(8 hunks)server/server_test.go(3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- server/server.go
🔇 Additional comments (5)
server/server_test.go (5)
62-62: LGTM! Completion capability correctly added to test.The addition of
WithCompletions()to the "All capabilities" test case ensures that the completion functionality is properly tested alongside other capabilities.
91-91: LGTM! Completion capability assertion follows existing pattern.The assertion
assert.NotNil(t, initResult.Capabilities.Completion)is consistent with how other capabilities are validated in this test.
1463-1479: LGTM! Well-structured test setup for completion functionality.The test setup correctly:
- Creates a server with a prompt containing an argument with a completion handler
- Uses a simple completion logic (appending "bar") that's easy to verify in tests
- Follows the established pattern for prompt creation in other tests
The completion handler implementation is clean and testable.
1481-1564: Excellent test coverage for completion scenarios.The test cases comprehensively cover:
- Successful completion: Validates that the completion handler is invoked and returns expected values
- No matching handler: Ensures graceful handling when no completion handler exists for an argument
- Missing prompt: Verifies proper error handling with
INVALID_PARAMSerror codeThe JSON-RPC message structures follow the MCP specification correctly, and the assertions validate both success and error scenarios appropriately.
1567-1574: LGTM! Test execution follows established patterns.The test execution loop and validation structure is consistent with other test functions in this file, ensuring maintainability and readability.
✨ 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.
🪧 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
@coderabbitaiin a new review comment at the desired location with your query. Examples:@coderabbitai explain this code block.@coderabbitai modularize this function.
- PR comments: Tag
@coderabbitaiin 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 pauseto pause the reviews on a PR.@coderabbitai resumeto resume the paused reviews.@coderabbitai reviewto trigger an incremental review. This is useful when automatic reviews are disabled for the repository.@coderabbitai full reviewto do a full review from scratch and review all the files again.@coderabbitai summaryto regenerate the summary of the PR.@coderabbitai generate docstringsto generate docstrings for this PR.@coderabbitai generate sequence diagramto generate a sequence diagram of the changes in this PR.@coderabbitai resolveresolve all the CodeRabbit review comments.@coderabbitai configurationto show the current CodeRabbit configuration for the repository.@coderabbitai helpto get help.
Other keywords and placeholders
- Add
@coderabbitai ignoreanywhere in the PR description to prevent this PR from being reviewed. - Add
@coderabbitai summaryto generate the high-level summary at a specific location in the PR description. - Add
@coderabbitaianywhere in the PR title to generate the title automatically.
CodeRabbit Configuration File (.coderabbit.yaml)
- You can programmatically configure CodeRabbit by adding a
.coderabbit.yamlfile 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.
@ezynda3 could you trigger the workflows again? I had to add another commit for docs and tests
@lariel-fernandes @ezynda3 is this going to be merged any time soon?