package main

import (
	"errors"
	"io"

	"github.com/modelcontextprotocol/go-sdk/mcp"
	"github.com/spf13/cobra"
)

func newServeCommand(opts *options) *cobra.Command {
	return &cobra.Command{
		Use:   "serve",
		Short: "Serve the DevOps operation tools over stdio MCP",
		Long: `Serve the DevOps operation tools over stdio MCP.

Point an MCP client at this command, for example:

  {
    "mcpServers": {
      "devops-operation": {
        "command": "operation-mcp",
        "args": ["serve", "--enable-write"],
        "env": { "DEVOPS_API_KEY": "<agent key>" }
      }
    }
  }`,
		Args: cobra.NoArgs,
		RunE: func(cmd *cobra.Command, _ []string) error {
			server, err := opts.newServer()
			if err != nil {
				return err
			}

			// stdout is the MCP transport, so nothing else may be written to it.
			cmd.SilenceUsage = true

			// A client that closes stdin is disconnecting, not failing.
			if err := server.Run(cmd.Context(), &mcp.StdioTransport{}); err != nil && !errors.Is(err, io.EOF) {
				return err
			}
			return nil
		},
	}
}
