当前位置: 首页 > news >正文

go构建sse服务端

package mainimport ("context""errors""fmt""log""net/http""os""os/signal""syscall""time""github.com/ThinkInAIXYZ/go-mcp/protocol""github.com/ThinkInAIXYZ/go-mcp/server""github.com/ThinkInAIXYZ/go-mcp/transport""github.com/gin-gonic/gin"
)type currentTimeReq struct {Timezone string `json:"timezone" description:"current time timezone"`
}func main() {messageEndpointURL := "/message"sseTransport, mcpHandler, err := transport.NewSSEServerTransportAndHandler(messageEndpointURL)if err != nil {log.Panicf("new sse transport and hander with error: %v", err)}mcpServer, err := server.NewServer(sseTransport,server.WithServerInfo(protocol.Implementation{Name:    "mcp-example",Version: "1.0.0",}),)if err != nil {panic(err)}tool, err := protocol.NewTool("current_time", "Get current time with timezone, Asia/Shanghai is default", currentTimeReq{})if err != nil {panic(fmt.Sprintf("Failed to create tool: %v", err))}mcpServer.RegisterTool(tool, currentTime)router := gin.Default()router.GET("/sse", func(ctx *gin.Context) {mcpHandler.HandleSSE().ServeHTTP(ctx.Writer, ctx.Request)})router.POST(messageEndpointURL, func(ctx *gin.Context) {mcpHandler.HandleMessage().ServeHTTP(ctx.Writer, ctx.Request)})httpServer := &http.Server{Addr:        ":8080",Handler:     router,IdleTimeout: time.Minute,}errCh := make(chan error, 3)go func() {errCh <- mcpServer.Run()}()go func() {if err = httpServer.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {errCh <- err}}()if err = signalWaiter(errCh); err != nil {panic(fmt.Sprintf("signal waiter: %v", err))}ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)defer cancel()httpServer.RegisterOnShutdown(func() {if err = mcpServer.Shutdown(ctx); err != nil {panic(err)}})if err = httpServer.Shutdown(ctx); err != nil {panic(err)}
}func currentTime(_ context.Context, request *protocol.CallToolRequest) (*protocol.CallToolResult, error) {req := new(currentTimeReq)if err := protocol.VerifyAndUnmarshal(request.RawArguments, &req); err != nil {return nil, err}text := fmt.Sprintf(`current time is %s`, time.Now().Format(time.DateTime))fmt.Println(text)return &protocol.CallToolResult{Content: []protocol.Content{&protocol.TextContent{Type: "text",Text: text,},},}, nil
}func signalWaiter(errCh chan error) error {signalToNotify := []os.Signal{syscall.SIGINT, syscall.SIGHUP, syscall.SIGTERM}if signal.Ignored(syscall.SIGHUP) {signalToNotify = []os.Signal{syscall.SIGINT, syscall.SIGTERM}}signals := make(chan os.Signal, 1)signal.Notify(signals, signalToNotify...)select {case sig := <-signals:switch sig {case syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM:log.Printf("Received signal: %s\n", sig)// graceful shutdownreturn nil}case err := <-errCh:return err}return nil
}
```go
http://www.fuzeviewer.com/news/517/

相关文章:

  • 1027
  • 关系运算符逻辑运算符
  • 《程序员修炼之道》 阅读笔记三
  • 第四篇:docker底层原理
  • 关于springboot+Servlet报错404的问题
  • Codechef Painting Tree 题解 [ 蓝 ] [ 树形 DP ] [ 概率期望 ] [ 分类讨论 ]
  • 【CI130x 离在线】如何运行 curl 脚本
  • 这才是真正的AI NAS!极空间私有云Z2Ultra评测
  • 新东方第三节课名言作文
  • 十月阅读_3
  • 中考_体育
  • 常见问题处理 --- phpstudy启动mysql失败
  • 20232308 2025-2026-1 《网络与系统攻防技术》实验三实验报告
  • 【密码学实战】openHiTLS PKCS12命令行程序: PKCS12文件生成与解析
  • 「CTSC2017-游戏」题解
  • vue3 vue3-form-element表单生成工具 输入框增加后缀
  • 20232402 2025-2026-1 《网络与系统攻防技术》实验三实验报告
  • 掘金2025年:数字化商业浪潮下,如何选对平台与伙伴?一站式多商户商城系统推荐榜发布,多商户商城代理招募/多商户项目合伙人加盟/一站式开店代理项目加盟
  • 为医疗器械行业搭建“数字桥梁”,破解协同效率与合规难题
  • PostgreSQL 服务版
  • 20232307 2025-2026-1 《网络与系统攻防技术》实验三实验报告
  • 2025年10月办公家具公司评价榜:基于真实数据的权威推荐清单
  • vue+antv/x6项目使用问题
  • 《程序员修炼之道:从小工到专家》前五分之一观后感
  • 坐标系与投影关系
  • 用gdb的动态视角看ret2text的实现
  • 1027随笔
  • ask_skill
  • SVN 主分支合并之通过主分支合并子分支执行流程
  • 现代c++编程体验2