1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
// Copyright (C) 2025 David M. Cotter
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
#pragma once
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QObject>
#include <QTcpServer>
#include <QTcpSocket>
#include <QTimer>
#include "httpparser.h"
#include "httpresponse.h"
#include "mcpcommands.h"
namespace Mcp::Internal {
class McpServer : public QObject
{
Q_OBJECT
public:
explicit McpServer(QObject *parent = nullptr);
~McpServer();
bool start(quint16 port = 3001);
void stop();
bool isRunning() const;
quint16 getPort() const;
// Public method to call MCP methods directly
QJsonObject callMCPMethod(
const QString &method, const QJsonObject ¶ms = {}, const QJsonValue &id = {});
private slots:
void handleNewConnection();
void handleClientData();
void handleClientDisconnected();
private:
QJsonObject createErrorResponse(
int code, const QString &message, const QJsonValue &id = QJsonValue::Null);
QJsonObject createSuccessResponse(
const QJsonValue &result, const QJsonValue &id = QJsonValue::Null);
void sendResponse(QTcpSocket *client, const QJsonObject &response);
// HTTP handling methods
bool isHttpRequest(const QByteArray &data);
void handleHttpRequest(QTcpSocket *client, const HttpParser::HttpRequest &request);
void sendHttpResponse(QTcpSocket *client, const QByteArray &httpResponse);
void onHttpGet(QTcpSocket *client, const HttpParser::HttpRequest &request);
void onHttpPost(QTcpSocket *client, const HttpParser::HttpRequest &request);
void onHttpOptions(QTcpSocket *client, const HttpParser::HttpRequest &request);
// SSE specific helpers
void handleSseClient(QTcpSocket *client);
void broadcastSseMessage(const QJsonObject &msg);
private:
using MethodHandler
= std::function<QJsonObject(const QJsonObject ¶ms, const QJsonValue &id)>;
QHash<QString, MethodHandler> m_methods;
using ToolHandler = std::function<QJsonObject(const QJsonObject ¶ms)>;
QHash<QString, ToolHandler> m_toolHandlers;
QJsonArray m_toolList;
QTcpServer *m_tcpServerP;
HttpParser *m_httpParserP;
QList<QTcpSocket *> m_clients;
QList<QTcpSocket *> m_sseClients;
McpCommands *m_commandsP;
quint16 m_port;
QHash<QTcpSocket*, QByteArray> m_partialData;
};
} // namespace Mcp::Internal
|