Repository navigation
feat: add MCP endpoint for sending messages #1066
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
Merged
Merged
Changes from 4 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
d712eba
feat: add MCP endpoint for sending messages
RedwindA b72aa85
docs: note click_url and big_image_url are Android-only
RedwindA 294c1bf
test: cover MCP auth guard and database error paths
RedwindA 0aa523a
docs: move MCP documentation to the website
RedwindA 3ae2545
refactor: rename GOTIFY_SERVER_MCP_ENABLED to GOTIFY_MCP_ENABLED
RedwindA File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,115 @@ | ||
| package api | ||
|
|
||
| import ( | ||
| "context" | ||
| "errors" | ||
| "fmt" | ||
| "net/http" | ||
|
|
||
| "github.com/gin-gonic/gin" | ||
| "github.com/gotify/server/v3/auth" | ||
| "github.com/gotify/server/v3/model" | ||
| "github.com/modelcontextprotocol/go-sdk/mcp" | ||
| "github.com/rs/zerolog/log" | ||
| ) | ||
|
|
||
| type mcpAppKey struct{} | ||
|
|
||
| // MCPAPI provides a Model Context Protocol endpoint which lets AI agents send messages | ||
| // with an application token. | ||
| type MCPAPI struct { | ||
| messages *MessageAPI | ||
| version string | ||
| schemaCache *mcp.SchemaCache | ||
| handler http.Handler | ||
| } | ||
|
|
||
| // SendMessageInput holds the arguments of the send_message tool. | ||
| type SendMessageInput struct { | ||
| Message string `json:"message" jsonschema:"The message content."` | ||
| Title string `json:"title,omitempty" jsonschema:"The message title. Defaults to the application name."` | ||
| Priority *int `json:"priority,omitempty" jsonschema:"The message priority. Higher values are more urgent: 0 is silent, 1-3 low, 4-7 normal, 8-10 high. Defaults to the application default priority."` | ||
| Markdown bool `json:"markdown,omitempty" jsonschema:"Whether the message content should be rendered as Markdown."` | ||
| ClickURL string `json:"click_url,omitempty" jsonschema:"A URL to open when the notification is clicked. Only supported by the Android client."` | ||
| BigImageURL string `json:"big_image_url,omitempty" jsonschema:"A URL of an image to show in the notification. Only supported by the Android client."` | ||
| } | ||
|
|
||
| // NewMCP creates a new MCPAPI. | ||
| func NewMCP(messages *MessageAPI, version string) *MCPAPI { | ||
| a := &MCPAPI{messages: messages, version: version, schemaCache: mcp.NewSchemaCache()} | ||
| a.handler = mcp.NewStreamableHTTPHandler(a.serverForRequest, &mcp.StreamableHTTPOptions{ | ||
| Stateless: true, | ||
| JSONResponse: true, | ||
| // Authentication is done via application tokens, and gotify is commonly run behind a reverse proxy on localhost. | ||
| DisableLocalhostProtection: true, | ||
| }) | ||
| return a | ||
| } | ||
|
|
||
| // Handle serves the MCP endpoint, the request must be authenticated with an application token. | ||
| func (a *MCPAPI) Handle(ctx *gin.Context) { | ||
| app := auth.GetApplication(ctx) | ||
| if app == nil { | ||
| ctx.AbortWithError(403, errors.New("the mcp endpoint requires an application token")) | ||
| return | ||
| } | ||
| req := ctx.Request.WithContext(context.WithValue(ctx.Request.Context(), mcpAppKey{}, app)) | ||
| a.handler.ServeHTTP(ctx.Writer, req) | ||
| } | ||
|
|
||
| func (a *MCPAPI) serverForRequest(req *http.Request) *mcp.Server { | ||
| app, ok := req.Context().Value(mcpAppKey{}).(*model.Application) | ||
| if !ok { | ||
| return nil | ||
| } | ||
| server := mcp.NewServer(&mcp.Implementation{Name: "gotify", Version: a.version}, &mcp.ServerOptions{SchemaCache: a.schemaCache}) | ||
| mcp.AddTool(server, &mcp.Tool{ | ||
| Name: "send_message", | ||
| Description: fmt.Sprintf("Send a push notification via Gotify as the application %q.", app.Name), | ||
| Annotations: &mcp.ToolAnnotations{Title: "Send message", DestructiveHint: new(bool)}, | ||
| }, func(_ context.Context, _ *mcp.CallToolRequest, in SendMessageInput) (*mcp.CallToolResult, any, error) { | ||
| return a.sendMessage(app, in) | ||
| }) | ||
| return server | ||
| } | ||
|
|
||
| func (a *MCPAPI) sendMessage(app *model.Application, in SendMessageInput) (*mcp.CallToolResult, any, error) { | ||
| if in.Message == "" { | ||
| return nil, nil, errors.New("message must not be empty") | ||
| } | ||
| msg := &model.CreateMessage{ | ||
| Title: in.Title, | ||
| Message: in.Message, | ||
| Priority: in.Priority, | ||
| Extras: mcpExtras(in), | ||
| } | ||
| created, err := a.messages.createMessage(app, msg) | ||
| if err != nil { | ||
| log.Error().Err(err).Uint("app_id", app.ID).Msg("MCP: could not create message") | ||
| return nil, nil, errors.New("failed to send message") | ||
| } | ||
| return &mcp.CallToolResult{ | ||
| Content: []mcp.Content{&mcp.TextContent{Text: fmt.Sprintf("Message sent (id %d).", created.ID)}}, | ||
| }, nil, nil | ||
| } | ||
|
|
||
| func mcpExtras(in SendMessageInput) map[string]any { | ||
| extras := map[string]any{} | ||
| if in.Markdown { | ||
| extras["client::display"] = map[string]any{"contentType": "text/markdown"} | ||
| } | ||
| notification := map[string]any{} | ||
| if in.ClickURL != "" { | ||
| notification["click"] = map[string]any{"url": in.ClickURL} | ||
| } | ||
| if in.BigImageURL != "" { | ||
| notification["bigImageUrl"] = in.BigImageURL | ||
| } | ||
| if len(notification) > 0 { | ||
| extras["client::notification"] = notification | ||
| } | ||
| if len(extras) == 0 { | ||
| return nil | ||
| } | ||
| return extras | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| package api | ||
|
|
||
| import ( | ||
| "net/http/httptest" | ||
| "testing" | ||
|
|
||
| "github.com/gin-gonic/gin" | ||
| "github.com/gotify/server/v3/mode" | ||
| "github.com/gotify/server/v3/test/testdb" | ||
| "github.com/stretchr/testify/assert" | ||
| ) | ||
|
|
||
| func TestMCP_HandleWithoutApplication(t *testing.T) { | ||
| mode.Set(mode.TestDev) | ||
| recorder := httptest.NewRecorder() | ||
| ctx, _ := gin.CreateTestContext(recorder) | ||
| ctx.Request = httptest.NewRequest("POST", "/mcp", nil) | ||
|
|
||
| NewMCP(&MessageAPI{}, "1.0.0").Handle(ctx) | ||
|
|
||
| assert.Equal(t, 403, recorder.Code) | ||
| assert.Len(t, ctx.Errors, 1) | ||
| } | ||
|
|
||
| func TestMCP_ServerForRequestWithoutApplication(t *testing.T) { | ||
| a := NewMCP(&MessageAPI{}, "1.0.0") | ||
| assert.Nil(t, a.serverForRequest(httptest.NewRequest("POST", "/mcp", nil))) | ||
| } | ||
|
|
||
| func TestMCP_SendMessageDatabaseError(t *testing.T) { | ||
| mode.Set(mode.TestDev) | ||
| db := testdb.NewDBWithDefaultUser(t) | ||
| app := db.User(5).NewAppWithToken(3, "apptoken") | ||
| db.Close() | ||
|
|
||
| a := NewMCP(&MessageAPI{DB: db}, "1.0.0") | ||
| res, _, err := a.sendMessage(app, SendMessageInput{Message: "hi"}) | ||
|
|
||
| assert.Nil(t, res) | ||
| assert.EqualError(t, err, "failed to send message") | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.