HTTP to MCP protocol conversion method based on SSE

By adopting an SSE-based HTTP to MCP protocol conversion method, the problem that HTTP interface services cannot meet the requirements of LLM streaming returns is solved, realizing real-time display of streaming responses and simplifying interface integration, thereby improving the real-time performance and compatibility of the system.

CN121334260APending Publication Date: 2026-01-13SHANDONG INSPUR DIGITAL BUSINESS TECHNOLOGY CO LTD
View PDF 0 Cites 1 Cited by

Patent Information

Application Number
CN202511314893.1
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2025-09-15
Publication Date
2026-01-13

AI Technical Summary

Technical Problem

Traditional HTTP interface services cannot meet the requirements of streaming output and continuous status push of Large Language Model (LLM), resulting in insufficient real-time performance, lack of event-driven capabilities, and inconsistent interface structures, which affect user experience and service quality.

Method used

An HTTP-to-MCP protocol conversion method based on SSE is adopted. By receiving client requests, extracting key parameters, converting them into parameters that conform to the HTTP service interface specification, constructing HTTP requests, parsing HTTP response data and mapping it to the MCP protocol format, generating streaming responses and pushing them to the client.

Benefits of technology

It enables real-time display of streaming messages, enhances real-time performance and compatibility, simplifies the integration of different HTTP interfaces, reduces migration costs, and improves the system's flexibility and adaptability.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN121334260A_ABST
    Figure CN121334260A_ABST
Patent Text Reader

Abstract

The invention provides an SSE-based HTTP to MCP protocol conversion method, and relates to the technical field of network communication and artificial intelligence engineering integration, and the method comprises the steps: receiving a request sent by a client through an SSE protocol, and extracting key parameters in the request; according to a preset rule mapping configuration, converting the key parameter into a parameter conforming to an original HTTP service interface specification, and constructing an HTTP request; sending the HTTP request to a target HTTP service, and obtaining HTTP response data; analyzing the HTTP response data, and mapping and packaging the HTTP response data according to the upper and lower field specifications of the MCP protocol; and segmenting the packaged MCP protocol data according to an SSE protocol format to generate a streaming response, and pushing the streaming response to a client in real time.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This application belongs to the field of engineering integration technology of network communication and artificial intelligence, and specifically relates to an HTTP to MCP protocol conversion method based on SSE. Background Technology

[0002] With the rapid development of artificial intelligence technology, especially the increasingly widespread application of Large Language Models (LLM) and intelligent agent architectures, AI engineering platforms are gradually evolving from single model invocation to multimodal interaction, task closure, and real-time feedback. Against this backdrop, the Model Context Protocol (MCP), as a standardized interface specification, is gradually becoming a key support for interoperability between different LLM platforms. MCP supports context management, tool invocation, asynchronous callbacks, and other functions, improving the engineering level and platform compatibility of model services.

[0003] However, while traditional HTTP interface services boast good deployment maturity and broad compatibility, their synchronous request-response model struggles to meet the new demands of LLM's streaming output and continuous status updates. Specifically, this manifests in issues such as inability to provide real-time performance, lack of event-driven capabilities, and inconsistent interface structures, severely impacting user experience and service quality. Summary of the Invention

[0004] This application provides an SSE-based HTTP to MCP protocol conversion method to solve one of the aforementioned technical problems.

[0005] The technical solution adopted in this application is as follows:

[0006] This application provides an SSE-based HTTP to MCP protocol conversion method, including:

[0007] Receive requests sent by clients via the SSE protocol and extract key parameters from the requests;

[0008] According to the preset rule mapping configuration, the key parameters are converted into parameters that conform to the original HTTP service interface specification, and an HTTP request is constructed.

[0009] Send the HTTP request to the target HTTP service and obtain the HTTP response data;

[0010] The HTTP response data is parsed, and mapped and encapsulated according to the context field specification of the MCP protocol;

[0011] The encapsulated MCP protocol data is segmented according to the SSE protocol format to generate a streaming response, which is then pushed to the client in real time.

[0012] According to one embodiment of this application, the receiving client sending a request via the SSE protocol includes:

[0013] Listen for connection requests using the SSE protocol and parse the session identifier, user identity information, and request content in the request header;

[0014] Verify the validity of the session identifier and record the request timestamp.

[0015] According to one embodiment of this application, constructing an HTTP request based on a preset rule mapping configuration includes:

[0016] The rules engine matches the mapping relationship between the field names of the HTTP interface and the MCP protocol context fields.

[0017] Convert JSON-formatted parameters in an SSE request to corresponding key-value pairs in an HTTP request, or parse XML-formatted parameters using XPath and map them to the HTTP request body.

[0018] According to one embodiment of this application, sending an HTTP request and obtaining HTTP response data includes:

[0019] The constructed HTTP request is forwarded to the target HTTP service through a middleware proxy;

[0020] Receive the complete response data returned by the target HTTP service and verify the format and content integrity of the response data.

[0021] According to one embodiment of this application, parsing the HTTP response data and mapping it to MCP protocol data includes:

[0022] Extract the status code, content body, and metadata from the HTTP response;

[0023] The content body is dynamically populated according to the template structure of the MCP protocol to generate context fields that conform to the MCP protocol;

[0024] The metadata is converted into an event type identifier in the MCP protocol and bound to the content body.

[0025] According to one embodiment of this application, generating an SSE streaming response and pushing it to the client includes:

[0026] According to the semantic boundaries or preset segmentation rules defined in the MCP protocol, the encapsulated data is split into multiple SSE message segments;

[0027] Add an event identifier and timestamp to each SSE message segment, and push them to the client segment by segment through the streaming channel of the SSE protocol.

[0028] According to one embodiment of this application, it also includes:

[0029] During the generation of SSE streaming responses, if an asynchronous callback event of LLM calling an external tool is detected, the callback data is received and the MCP context state is updated.

[0030] Based on the updated context state, the model inference process is retried, and the results are pushed to the client as a new SSE message segment.

[0031] According to one embodiment of this application, it also includes:

[0032] Record key operation logs throughout the entire conversion process, including request parameters, response content, rule mapping matching status, and exception information;

[0033] Provides a visual monitoring interface to display log data and system operating status.

[0034] A second aspect of this application provides a computer-readable storage medium having a program stored thereon that, when executed by a processor, implements the steps described in the method.

[0035] A third aspect of this application provides an electronic device including a memory, a processor, and a program stored in the memory and executable on the processor, wherein the processor executes the program to implement the steps of the method as described.

[0036] Due to the adoption of the above technical solution, the beneficial effects achieved by this application are as follows:

[0037] This application constructs an HTTP request by receiving requests sent by clients based on the SSE protocol and converting them into parameters conforming to the original HTTP service interface specification. Subsequently, after obtaining the HTTP response, the data is mapped and encapsulated according to the MCP protocol, and finally a segmented SSE streaming response is generated and pushed to the client. This process allows the HTTP response, which was originally returned in one go, to be converted into a streaming message, greatly enhancing the ability to display in real time, and is particularly suitable for conversational or application scenarios that require immediate feedback.

[0038] This application utilizes a pre-defined rule mapping configuration to convert key parameters in HTTP requests into a format conforming to the MCP protocol. This not only simplifies the integration between HTTP interfaces provided by different vendors but also ensures consistency and stability across various application scenarios, thereby improving the overall system's compatibility and scalability.

[0039] This application achieves a non-intrusive protocol conversion without altering the original HTTP service's code logic. This means that existing systems can be smoothly upgraded to services supporting SSE / MCP without affecting existing business processes, significantly reducing migration costs and technical risks.

[0040] This application constructs a general-purpose middleware system that can not only serve as an L4 / L7 gateway layer component to perform functions such as protocol conversion, security control, and log tracing, but also easily adapt to various types of HTTP interfaces and service forms through a plug-in mechanism, further enhancing the system's flexibility and adaptability. Attached Figure Description

[0041] The accompanying drawings, which are included to provide a further understanding of this application and form part of this application, illustrate exemplary embodiments and are used to explain this application, but do not constitute an undue limitation of this application. In the drawings:

[0042] Figure 1 A flowchart illustrating an SSE-based HTTP to MCP protocol conversion method provided in this application embodiment;

[0043] Figure 2 This is a schematic diagram of the structure of an electronic device provided in an embodiment of this application.

[0044] Figure label:

[0045] 810, Processor; 820, Communication interface; 830, Memory; 840, Communication bus. Detailed Implementation

[0046] To more clearly illustrate the overall concept of this application, a detailed explanation is provided below with reference to the accompanying drawings.

[0047] Many specific details are set forth in the following description to provide a thorough understanding of this application. However, this application may also be implemented in other ways different from those described herein. Therefore, the scope of protection of this application is not limited to the specific embodiments disclosed below. It should be noted that, unless otherwise specified, the embodiments of this application and the features thereof can be combined with each other.

[0048] In this application, unless otherwise expressly specified and limited, the "above" or "below" of the second feature can mean that the first and second features are in direct contact, or that the first and second features are in indirect contact through an intermediate medium. In the description of this specification, references to terms such as "an embodiment," "some embodiments," "example," "specific example," or "some examples," etc., indicate that a specific feature, structure, material, or characteristic described in connection with that embodiment or example is included in at least one embodiment or example of this application. In this specification, the illustrative expressions of the above terms do not necessarily refer to the same embodiment or example. Furthermore, the specific features, structures, materials, or characteristics described can be combined in any suitable manner in one or more embodiments or examples.

[0049] Example 1

[0050] like Figure 1 As shown, an HTTP to MCP protocol conversion method based on SSE includes:

[0051] S100: Receive the request sent by the client via the SSE protocol and extract the key parameters from the request.

[0052] As described above, the middleware system listens for and processes SSE (Server-Sent Events) protocol requests from clients. First, the system establishes a connection with the client and begins listening for SSE requests. Once a request is received, the system parses the request content to extract key parameters, such as the session ID, user identity information, and the specific request content. These parameters are crucial for subsequently constructing HTTP requests and performing protocol conversion. In this way, it ensures that all necessary information from the original request is accurately transmitted to subsequent processing flows.

[0053] For example, suppose an online customer service platform uses an LLM Agent to provide intelligent response services. When a customer initiates an inquiry request, the request is sent to a protocol conversion middleware on the server side via the SSE protocol. Upon receiving the request, this middleware extracts key parameters such as the customer's unique identifier (used to distinguish different users' conversations), the current session state (e.g., whether it's a new session or a continuation of an existing one), and the content of the customer's question. This information is then further processed to facilitate subsequent calls to the appropriate HTTP service interface to obtain the answer.

[0054] It should be noted that, in specific implementation scenarios, in addition to the basic user identity information, more complex identity verification processes can be added to the above solutions, such as a security authentication mechanism based on OAuth 2.0, to ensure that only authorized users can access specific resources.

[0055] In specific implementation scenarios, based on the above solution, it should also be able to process binary data or other data input formats, in addition to text data, making the solution applicable to more diverse application scenarios, such as image recognition or voice interaction.

[0056] In specific implementation scenarios, based on the above solutions, administrators can dynamically configure request parsing rules according to different business needs or security policies. For example, they can add encryption requirements for certain specific fields or add new metadata fields for tracking and auditing purposes.

[0057] In specific implementation scenarios, based on the above solution, if any problems are encountered during the extraction of key parameters (such as missing necessary fields), the system should be able to provide clear error messages in a timely manner and guide the client on how to correct the request, thereby improving the robustness of the system and the user experience.

[0058] S200. According to the preset rule mapping configuration, the key parameters are converted into parameters that conform to the original HTTP service interface specification, and an HTTP request is constructed.

[0059] As described above, through predefined rule mapping configurations, the key parameters extracted from the SSE request are adapted and transformed into a form that can be recognized and processed by the target HTTP service. First, the system converts the parameters in the SSE request into the format required by the HTTP request based on predefined mapping rules (such as field names, format conversion rules, etc.). These rules can be statically configured or dynamically adjusted to adapt to different business needs or changes in service interfaces. Then, based on the transformed parameters, a complete HTTP request message is constructed, including the request method (GET / POST, etc.), URL, header information, and request body, ensuring that the request can correctly interact with the backend HTTP service.

[0060] For example, consider a smart customer service application where a customer sends a request containing question text and a user ID via the SSE protocol. Assume the target HTTP service needs to receive data in JSON format and requires specific field names (e.g., "question" for the question text and "userId" for the user). In this case, the system will map the "question content" field in the SSE request to "question" in the HTTP request body, and the "user identification information" to "userId," according to a pre-defined mapping configuration. Then, a POST request is constructed, with its body containing the two fields and their corresponding values, along with appropriate HTTP headers (e.g., Content-Type: application / json) so that the HTTP service can correctly parse and process the request.

[0061] It should be noted that, in specific implementation scenarios, in addition to directly extracting parameters from the SSE request, the above solution can also support obtaining supplementary information from other data sources (such as databases, caches, or other APIs) and incorporating it into the final HTTP request. This helps enrich the content of the request and provide more personalized or context-sensitive service responses.

[0062] In specific implementation scenarios, based on the above solutions, administrators or developers can easily manage and update rule mapping configurations through a graphical interface, quickly adapting to new business needs or service changes without modifying the underlying code. Furthermore, it supports applications that dynamically adjust rules based on different conditions (such as time, geographical location, etc.), enhancing the system's flexibility.

[0063] In specific implementation scenarios, additional security measures can be added to the parameter conversion process based on the above solutions. These measures could include encrypting sensitive information or verifying the authenticity of the request source to prevent malicious attacks or data leaks. Furthermore, integrating third-party security services can further enhance protection capabilities.

[0064] In specific implementation scenarios, building upon the above solutions, when encountering invalid or incomplete parameters, the system should be able to automatically detect and attempt to repair the error, or at least provide clear feedback to help the client correct the problem promptly. For serious error situations, the system should also have a certain self-recovery mechanism, such as retry logic or rollback to the default configuration, to maintain service continuity.

[0065] S300: Send the HTTP request to the target HTTP service and obtain the HTTP response data.

[0066] As described above, middleware functions as a proxy server, responsible for sending pre-constructed HTTP requests to the specified target HTTP service and receiving the response data returned by that service. In this process, middleware acts as a bridge, ensuring that requests reach their destination accurately and effectively handling feedback from the target service. To guarantee communication success and efficiency, middleware also needs to have certain fault tolerance mechanisms, such as retry strategies and timeout controls, to cope with network fluctuations or potential temporary server failures.

[0067] For example, continuing with the intelligent customer service application, suppose that after the previous steps, an HTTP POST request containing the customer's question text ("question":"How do I check my order status?") and user ID ("userId":"123456") has been constructed. Next, the middleware will send this request to the backend order management system's HTTP interface. Once the order management system receives the request and completes the corresponding processing (such as querying the database to retrieve the order status), it will return an HTTP response containing the query results (e.g., the order status is "shipped"). The middleware is then responsible for receiving this response and preparing to convert it into a data structure conforming to the MCP protocol format for use in subsequent steps.

[0068] It should be noted that in specific implementation scenarios, in addition to the basic retry logic, more complex error handling strategies can be introduced based on the above solutions. For example, different remedial measures can be taken based on different HTTP status codes (such as attempting to reroute to a backup server for 500 series errors). Furthermore, a health check function can be set up to periodically monitor the status of the target HTTP service and provide early warnings of potential service interruption risks.

[0069] In specific implementation scenarios, based on the above solutions, a load balancing algorithm can be integrated to automatically select the optimal path to send HTTP requests when facing high concurrency requests, thereby optimizing resource utilization efficiency. This not only improves system throughput but also enhances the stability of the overall architecture.

[0070] In specific implementation scenarios, based on the above solutions, encryption technologies (such as HTTPS) can be used to protect the security of data transmission and prevent the leakage of sensitive information throughout the entire request sending and response receiving process. Simultaneously, authentication steps can be added to ensure that only legitimate requests can access specific HTTP services.

[0071] In specific implementation scenarios, based on the above solution, detailed log records can be added for each request and response, including key indicators such as request time, response time, and processing result. Based on this data, the system can perform real-time performance monitoring, promptly identify and resolve bottlenecks, and continuously optimize service performance.

[0072] S400. Parse the HTTP response data and map and encapsulate the HTTP response data according to the context field specification of the MCP protocol.

[0073] As described above, the system needs to parse the response data received from the target HTTP service and reorganize this data into a format conforming to the MCP standard, according to the context field specification of the MCP (Model Context Protocol). First, the system checks the HTTP response status code to confirm whether the request was successfully processed; then, it extracts the content body and other relevant metadata (such as header information) from the response. Next, using a predefined rule mapping configuration, the extracted data elements are converted into context fields specified in the MCP protocol. This step ensures that even if the output format of the original HTTP interface varies, the data ultimately delivered to the client remains consistent and standardized.

[0074] For example, suppose the intelligent customer service application receives a question from the front end about checking the order status and forwards it to the backend order management system through the previous steps. The order management system returns an HTTP response containing the order status (e.g., "shipped"), estimated delivery time, and other relevant information. In this step, the middleware parses this response and extracts all the necessary information. For instance, "order status" is mapped to the "status" field in the MCP context, while "estimated delivery time" corresponds to "estimatedDeliveryTime". In this way, the information that was originally scattered across different fields is integrated into a unified, structured response, facilitating subsequent processing and display.

[0075] It should be noted that, in specific implementation scenarios, intelligent algorithms can be introduced on top of the above solutions to automatically identify and match the relationships between unknown or changing HTTP response fields and MCP context fields, reducing the workload of manual configuration and improving system flexibility. For example, when encountering a new response field, the system can infer the most likely mapping method based on existing patterns.

[0076] In specific implementation scenarios, building upon the above solutions and considering globalization needs, the system can support field mapping and data encapsulation in multiple language environments. This means that response data, whether in English, Chinese, or other languages, can be seamlessly converted into a unified MCP format, thereby enhancing the platform's internationalization capabilities.

[0077] In specific implementation scenarios, based on the above solutions, data validation and cleanup mechanisms can be added while parsing HTTP response data to ensure that only legitimate and valid data is encapsulated in the MCP response. This includes removing duplicate or unnecessary information and correcting formatting errors, which helps improve the quality of the final output.

[0078] In specific implementation scenarios, based on the above solution, administrators can also update the MCP protocol template in real time according to changes in business needs. For example, during promotional activities, new fields can be quickly added to record discount information or other temporary promotional details, taking effect immediately without downtime maintenance.

[0079] In specific implementation scenarios, based on the above solutions, machine learning techniques can be used to analyze large amounts of historical data and user feedback to continuously optimize field mapping strategies and encapsulation processes, thereby improving conversion efficiency and accuracy. This approach is particularly suitable for application scenarios with complex and ever-changing response data.

[0080] The S500 segments the encapsulated MCP protocol data into stream responses according to the SSE protocol format and pushes them to the client in real time.

[0081] As described above, data encapsulated according to the MCP protocol specification is converted into a format conforming to the SSE (Server-Sent Events) protocol and pushed to the client as a streaming response. First, the system segments the encapsulated MCP data into multiple independent message segments based on preset rules or standards (such as content length, semantic boundaries, etc.). Each message segment is assigned a unique event identifier and timestamp so that the client can correctly identify and process these messages. Then, these message segments are sent to the client one by one in the format specified by the SSE protocol, achieving true streaming transmission. This allows the client to begin processing immediately after receiving partial data, without waiting for the entire response to complete.

[0082] For example, continuing with the intelligent customer service application, suppose that after the previous steps, we have obtained information about the order status (such as "status": "shipped" and "estimatedDeliveryTime": "2025-07-15"). In this step, the middleware will package this information according to the requirements of the SSE protocol. For example, it might create two messages: one containing the order status information and the other containing the estimated delivery time. Each message will be accompanied by an event ID (such as id:1 for the first message, id:2 for the second message) and a timestamp (such as data:{"status":"shipped","timestamp":"2025-07-10T10:35:00Z"}). Then, these messages will be pushed to the client in real time, allowing users to see updated information immediately.

[0083] It should be noted that, in specific implementation scenarios, in addition to dividing message segments based on fixed rules (such as content length or semantic boundaries), the segmentation strategy can be dynamically adjusted according to real-time network conditions or the specific needs of the client, based on the above solution. For example, when network conditions are poor, smaller message segments can be selected to reduce latency; while when network conditions are good, the message segment size can be appropriately increased to improve efficiency.

[0084] In specific implementation scenarios, the concept of message priority can be introduced based on the above solutions, allowing certain types of messages (such as urgent notifications or critical updates) to be processed and pushed with priority over other messages. This helps ensure that the most important or urgent information reaches the client as quickly as possible, improving the user experience.

[0085] In specific implementation scenarios, the system can be expanded to support multi-channel SSE transmission to adapt to different application needs, building upon the above solution. This means that a single client can simultaneously receive different types of messages through multiple connections, thereby optimizing resource utilization and improving response speed.

[0086] In specific implementation scenarios, based on the above solution, while pushing streaming responses, clients can also send feedback information to the server (such as confirming receipt of a message or requesting a resend of a lost message). This two-way communication mechanism not only enhances the robustness of the system but also provides more possibilities for interaction.

[0087] In specific implementation scenarios, personalized message push services can be provided based on user preferences or historical behavior patterns, building upon the above solutions. For example, for users who frequently query specific types of information, relevant data can be prepared in advance in the background, and this information can be pushed to them first, improving user experience satisfaction.

[0088] According to one embodiment of this application, the receiving client sending a request via the SSE protocol includes:

[0089] Listen for connection requests using the SSE protocol and parse the session identifier, user identity information, and request content in the request header;

[0090] Verify the validity of the session identifier and record the request timestamp.

[0091] As mentioned above, the system first needs to establish a listening mechanism to wait for and receive SSE connection requests initiated by clients. This means that the system must keep an open communication port to accept new SSE connections at any time. When a client attempts to establish a connection, the system will detect this request and prepare for further processing.

[0092] Once a connection request is received, the system will begin parsing the request header. This header contains several key pieces of information, such as the session ID, user identity information, and other metadata or custom fields that may be included in the request header.

[0093] Session identifiers are typically used to distinguish different client sessions, ensuring that each user's interactions are independent and orderly. User identity information is used to identify a specific user; this could be a username, user ID, or other form of authentication token.

[0094] The request content refers to the specific information that the client wishes to send through this connection. It may be included directly in the initial request or sent as part of a subsequent event.

[0095] After obtaining the session identifier, the system needs to verify its validity. This step ensures that only legitimate sessions can continue communication. The verification process may involve checking whether the session identifier exists in the system's session management database or confirming whether it meets preset security standards.

[0096] If the session identifier is invalid or has expired, the system should reject the connection request and may choose to return an error message to the client prompting them to log in again or update the session information.

[0097] Finally, the system records the exact time the request was received, i.e., the request timestamp. This is crucial for tracking session activity, analyzing performance metrics, and implementing timeout control. By saving the request timestamp, the system can monitor session activity, ensuring that inactive sessions are promptly cleaned up, thereby freeing up resources and improving security.

[0098] According to one embodiment of this application, constructing an HTTP request based on a preset rule mapping configuration includes:

[0099] The rules engine matches the mapping relationship between the field names of the HTTP interface and the MCP protocol context fields.

[0100] Convert JSON-formatted parameters in an SSE request to corresponding key-value pairs in an HTTP request, or parse XML-formatted parameters using XPath and map them to the HTTP request body.

[0101] As mentioned above, the system has a built-in rules engine that stores and manages one or more sets of predefined field mapping rules. These rules are used to establish the correspondence between context fields in the MCP protocol and the fields that the target HTTP interface expects to receive.

[0102] For example, the MCP protocol might use "user_id" to represent a user identifier, while the target HTTP interface expects to receive a field named "userId". In this case, the rule engine will automatically identify and convert "user_id" to "userId" according to the configured mapping rules.

[0103] The rules engine supports multiple matching methods, such as exact matching, fuzzy matching, or regular expression matching, to adapt to the different naming conventions of different HTTP interfaces.

[0104] After receiving an SSE request from a client, the system typically extracts structured data, which may be a set of parameters in JSON or XML format.

[0105] If the data is in JSON format, the system will parse it into a combination of multiple fields and values, and according to the aforementioned field mapping rules, convert each field into the field name required by the target HTTP interface, and then encapsulate it into key-value pairs in the HTTP request (such as URL query parameters or form submission data).

[0106] If the data is in XML format, the system will use XPath expressions to locate and extract key node information. Then, following the same field mapping rules, the extracted information will be converted into the field names required by the HTTP interface and populated into the HTTP request body.

[0107] Finally, the system organizes all the converted parameters into a complete HTTP request, including the request method (such as GET, POST), the target URL, the request headers, and the request body, so that the request can be successfully sent to the target HTTP service for processing.

[0108] According to one embodiment of this application, sending an HTTP request and obtaining HTTP response data includes:

[0109] The constructed HTTP request is forwarded to the target HTTP service through a middleware proxy;

[0110] Receive the complete response data returned by the target HTTP service and verify the format and content integrity of the response data.

[0111] As mentioned above, the system includes a protocol conversion middleware that acts as a proxy layer between the client and the backend HTTP service. This middleware is responsible for receiving standard HTTP requests converted from the SSE protocol.

[0112] Upon receiving the HTTP request, the middleware will accurately forward the request to the corresponding HTTP service interface based on the configured target service address, port, and communication protocol.

[0113] During the forwarding process, the middleware can support multiple network protocols (such as HTTP / HTTPS) and communication methods (such as synchronous blocking or asynchronous non-blocking) to adapt to the technical implementation methods of different backend services.

[0114] The middleware also has connection management capabilities, which can maintain long-lived connections with backend services, control the number of concurrent requests, and handle retry mechanisms to improve the overall system stability and performance.

[0115] Once the target HTTP service has processed the request, it will return the result to the middleware as an HTTP response. This response typically includes a status code, response headers, and a response body.

[0116] After receiving the complete HTTP response, the middleware first checks the response status code. For example, 200 indicates success, 404 indicates resource not found, and 500 indicates an internal server error. This is used to make a preliminary judgment on whether the request was processed normally.

[0117] Next, the system will validate the data format of the response body to confirm whether it conforms to the expected structure, such as JSON, XML, or other custom formats. It will also verify the integrity of the response content, such as checking the existence of key fields and whether the data length is reasonable.

[0118] If abnormal response data or mismatched format is detected, the system can take corresponding actions according to preset strategies, such as logging, triggering alarms, returning a default response, or re-initiating the request, thereby ensuring the continuity and reliability of the service.

[0119] According to one embodiment of this application, parsing the HTTP response data and mapping it to MCP protocol data includes:

[0120] Extract the status code, content body, and metadata from the HTTP response;

[0121] The content body is dynamically populated according to the template structure of the MCP protocol to generate context fields that conform to the MCP protocol;

[0122] The metadata is converted into an event type identifier in the MCP protocol and bound to the content body.

[0123] As mentioned above, when the system receives the response from the target HTTP service, it first extracts key information from it, including the HTTP status code, the response body, and related metadata.

[0124] HTTP status codes are used to indicate the outcome of a request, such as 200 for success, 400 for client error, and 500 for server internal error.

[0125] The main content typically contains specific business data, which may be in JSON, XML, or other structured text formats, carrying the core response information of the request.

[0126] Metadata includes additional information in the response header, such as content type, encoding method, timestamp, and cache control strategy. This information can be used for subsequent data processing and encapsulation.

[0127] The content body is dynamically populated according to the template structure of the MCP protocol to generate context fields that conform to the MCP protocol:

[0128] The system has a built-in standard template structure that conforms to the MCP protocol definition. This template has multiple preset context fields, such as "status", "content", "tool_call", and "context_id", which are used to uniformly express various information in the model interaction process.

[0129] After parsing the content body of the HTTP response, the system will fill in the corresponding fields in the MCP template with the various parts of the original data according to the pre-configured field mapping rules.

[0130] For example, if an HTTP response contains an "answer" field, the system can map it to the "content" field in the MCP template according to the rules; if an "intent" field exists, it can be mapped to the "intent_type" field.

[0131] Once populated, a complete and semantically clear MCP context object is formed, providing a standardized data foundation for subsequent message encapsulation and push.

[0132] During the parsing of the HTTP response, the system will further process the extracted metadata, identify semantically meaningful information, and convert it into event type identifiers defined in the MCP protocol.

[0133] For example, if the response header contains a custom field "X-Event-Type:tool_response", the system can convert it to the event type "tool_response" in the MCP protocol to identify that the current response is a result feedback of a tool call.

[0134] In addition, the system also binds the event type to the previously populated MCP context content to ensure that the message category and purpose can be accurately identified when generating SSE messages in the future.

[0135] This binding mechanism helps clients to perform corresponding processing logic based on different event types, improving the system's scalability and interactivity.

[0136] According to one embodiment of this application, generating an SSE streaming response and pushing it to the client includes:

[0137] According to the semantic boundaries or preset segmentation rules defined in the MCP protocol, the encapsulated data is split into multiple SSE message segments;

[0138] Add an event identifier and timestamp to each SSE message segment, and push them to the client segment by segment through the streaming channel of the SSE protocol.

[0139] As mentioned above, after encapsulating the MCP protocol data, the system needs to segment the entire response content so that it can be sent step by step in a streaming manner.

[0140] Segmentation can be based on semantic boundaries defined in the MCP protocol, such as a complete context state change, the result feedback of a tool call, or a logical unit such as a piece of natural language output; or it can be based on system-preset segmentation rules, such as segmentation by character count, by JSON object level, or by the time order of response content.

[0141] Each segmented SSE message segment should maintain structural integrity and semantic clarity to ensure that the client can effectively parse and display any single message segment received.

[0142] To facilitate client identification and processing of different message types, the system attaches an event identifier (Event Type) to each SSE message segment to indicate the purpose or category of the data segment, such as "model_response", "tool_result", "context_update", etc.

[0143] In addition, the system will add a timestamp to each message to record the specific time when the message was generated or sent, which can be used by the client to perform operations such as message sorting, delay analysis or log tracking.

[0144] All message segments are encapsulated according to the format specified by the SSE protocol and pushed sequentially to the client through the established SSE long-lived connection channel. The client can begin processing and displaying the message immediately after receiving the first message segment, without waiting for all data transmission to complete, thus achieving a truly real-time streaming interactive experience.

[0145] According to one embodiment of this application, it also includes:

[0146] During the generation of SSE streaming responses, if an asynchronous callback event of LLM calling an external tool is detected, the callback data is received and the MCP context state is updated.

[0147] Based on the updated context state, the model inference process is retried, and the results are pushed to the client as a new SSE message segment.

[0148] As mentioned above, in the intelligent interaction process involving LLM, the model may decide to call an external tool (such as a database query, weather interface, payment system, etc.) based on the current dialogue context, and encapsulate the call instruction as a specific event and pass it to the execution component through the MCP protocol.

[0149] When the external tool completes its task, it sends an asynchronous callback event to the system, notifying the system that it has received the processing result. At this time, the system needs to listen for and capture this callback event to obtain the returned data carried within it.

[0150] After obtaining the callback data, the system will parse the data content according to the MCP protocol specification and bind it to the current dialogue context to update relevant fields in the MCP context, such as adding new status information, supplementing tool call results, or modifying the dialogue path.

[0151] This update operation ensures the consistency of the state throughout the entire model interaction process and provides the necessary input for subsequent model inference.

[0152] After updating the MCP context state, the system determines that the current dialogue process has not yet ended and the model still needs to process new context information.

[0153] The system then restarts the model inference process, submitting the updated context as input to the LLM for a new round of inference, generating new response content.

[0154] The newly generated content is then encapsulated again using the MCP protocol and processed through SSE message segmentation before being pushed to the client as new SSE message segments.

[0155] The client can continuously receive these new message segments without interrupting the connection, thus enabling a continuous interactive experience that is multi-round, dynamically changing, and supports asynchronous tool calls.

[0156] According to one embodiment of this application, it also includes:

[0157] Record key operation logs throughout the entire conversion process, including request parameters, response content, rule mapping matching status, and exception information;

[0158] Provides a visual monitoring interface to display log data and system operating status.

[0159] As mentioned above, the system sets up multiple log collection nodes throughout the protocol conversion process to automatically capture and record operational data at each key stage.

[0160] The recorded logs cover the entire process from the client initiating an SSE request, to constructing an HTTP request, calling the target service, parsing the response, encapsulating MCP data, generating SSE streaming messages, and finally pushing them to the client.

[0161] The logs contain detailed information about the original request parameters, the response content returned by the target HTTP service, the matching and execution status of field mapping rules, and any exceptions or errors that occurred during processing, such as timeouts, connection failures, and format mismatches.

[0162] These logs can be used for subsequent problem tracking, performance analysis, security auditing, and system optimization, providing comprehensive data support for operations and maintenance personnel and technical support teams.

[0163] In addition to logging, the system also integrates a visual monitoring module, providing an access interface for administrators or operations and maintenance platforms to view the current system's operational status in real time.

[0164] Through this interface, users can query and filter log information by time range, request source, service type, status code, and other dimensions to quickly locate the time and scope of the problem.

[0165] Meanwhile, the system can also display real-time operating metrics, such as concurrent requests, average response time, success rate, and anomaly rate, to help relevant personnel understand the overall load capacity and health of the system.

[0166] The visual interface supports functions such as chart display, log export, and alarm configuration, further improving the maintainability and observability of the system.

[0167] A second aspect of this application provides an electronic device, including a memory, a processor, and a computer program stored in the memory and executable on the processor, wherein the processor executes the program to implement the method described in any of the embodiments of the first aspect above.

[0168] Figure 2 An example is a schematic diagram of the physical structure of an electronic device, such as... Figure 2 As shown, the electronic device may include: a processor 810, a communication interface 820, a memory 830, and a communication bus 840, wherein the processor 810, the communication interface 820, and the memory 830 communicate with each other via the communication bus 840. The processor 810 may call logical instructions in the memory 830 to execute the method in any of the embodiments of the first aspect described above, the method including:

[0169] Receive requests sent by clients via the SSE protocol and extract key parameters from the requests;

[0170] According to the preset rule mapping configuration, the key parameters are converted into parameters that conform to the original HTTP service interface specification, and an HTTP request is constructed.

[0171] Send the HTTP request to the target HTTP service and obtain the HTTP response data;

[0172] The HTTP response data is parsed, and mapped and encapsulated according to the context field specification of the MCP protocol;

[0173] The encapsulated MCP protocol data is segmented according to the SSE protocol format to generate a streaming response, which is then pushed to the client in real time.

[0174] Furthermore, the logical instructions in the aforementioned memory 830 can be implemented as software functional units and, when sold or used as independent products, can be stored in a computer-readable storage medium. Based on this understanding, the technical solution of the present invention, or the part that contributes to the prior art, or a part of the technical solution, can be embodied in the form of a software product. This computer software product is stored in a storage medium and includes several instructions to cause a computer device (which may be a personal computer, server, or network device, etc.) to execute all or part of the steps of the methods described in the various embodiments of the present invention. The aforementioned storage medium includes various media capable of storing program code, such as USB flash drives, portable hard drives, read-only memory, random access memory, magnetic disks, or optical disks.

[0175] On the other hand, the present invention also provides a computer program product, the computer program product comprising a computer program, the computer program being able to be stored on a non-transitory computer-readable storage medium, and when the computer program is executed by a processor, the computer being able to perform the methods provided by the above methods, the method comprising:

[0176] Receive requests sent by clients via the SSE protocol and extract key parameters from the requests;

[0177] According to the preset rule mapping configuration, the key parameters are converted into parameters that conform to the original HTTP service interface specification, and an HTTP request is constructed.

[0178] Send the HTTP request to the target HTTP service and obtain the HTTP response data;

[0179] The HTTP response data is parsed, and mapped and encapsulated according to the context field specification of the MCP protocol;

[0180] The encapsulated MCP protocol data is segmented according to the SSE protocol format to generate a streaming response, which is then pushed to the client in real time.

[0181] In another aspect, the present invention also provides a non-transitory computer-readable storage medium having a computer program stored thereon, which, when executed by a processor, is implemented to perform the cigarette box image recognition method provided by the methods described above, the method comprising:

[0182] Receive requests sent by clients via the SSE protocol and extract key parameters from the requests;

[0183] According to the preset rule mapping configuration, the key parameters are converted into parameters that conform to the original HTTP service interface specification, and an HTTP request is constructed.

[0184] Send the HTTP request to the target HTTP service and obtain the HTTP response data;

[0185] The HTTP response data is parsed, and mapped and encapsulated according to the context field specification of the MCP protocol;

[0186] The encapsulated MCP protocol data is segmented according to the SSE protocol format to generate a streaming response, which is then pushed to the client in real time.

[0187] For any parts not mentioned in this application, existing technologies may be used or referenced.

[0188] The various embodiments in this specification are described in a progressive manner. The same or similar parts between the various embodiments can be referred to each other. Each embodiment focuses on describing the differences from other embodiments.

[0189] The above description is merely an embodiment of this application and is not intended to limit the scope of this application. Various modifications and variations can be made to this application by those skilled in the art. Any modifications, equivalent substitutions, improvements, etc., made within the spirit and principles of this application should be included within the scope of the claims of this application.

Claims

1. A method for converting HTTP to MCP protocol based on SSE, characterized in that, include: Receive requests sent by clients via the SSE protocol and extract key parameters from the requests; According to the preset rule mapping configuration, the key parameters are converted into parameters that conform to the original HTTP service interface specification, and an HTTP request is constructed. Send the HTTP request to the target HTTP service and obtain the HTTP response data; The HTTP response data is parsed, and mapped and encapsulated according to the context field specification of the MCP protocol; The encapsulated MCP protocol data is segmented according to the SSE protocol format to generate a streaming response, which is then pushed to the client in real time.

2. The method according to claim 1, characterized in that, The request sent by the receiving client via the SSE protocol includes: Listen for connection requests using the SSE protocol and parse the session identifier, user identity information, and request content in the request header; Verify the validity of the session identifier and record the request timestamp.

3. The method according to claim 1, characterized in that, The step of constructing an HTTP request according to a preset rule mapping configuration includes: The rules engine matches the mapping relationship between the field names of the HTTP interface and the MCP protocol context fields. Convert JSON-formatted parameters in an SSE request to corresponding key-value pairs in an HTTP request, or parse XML-formatted parameters using XPath and map them to the HTTP request body.

4. The method according to claim 1, characterized in that, The step of sending an HTTP request and obtaining HTTP response data includes: The constructed HTTP request is forwarded to the target HTTP service through a middleware proxy; Receive the complete response data returned by the target HTTP service and verify the format and content integrity of the response data.

5. The method according to claim 1, characterized in that, The process of parsing HTTP response data and mapping it to MCP protocol data includes: Extract the status code, content body, and metadata from the HTTP response; The content body is dynamically populated according to the template structure of the MCP protocol to generate context fields that conform to the MCP protocol; The metadata is converted into an event type identifier in the MCP protocol and bound to the content body.

6. The method according to claim 1, characterized in that, The generation of SSE streaming responses and their push to the client includes: According to the semantic boundaries or preset segmentation rules defined in the MCP protocol, the encapsulated data is split into multiple SSE message segments; Add an event identifier and timestamp to each SSE message segment, and push them to the client segment by segment through the streaming channel of the SSE protocol.

7. The method according to claim 1, characterized in that, Also includes: During the generation of SSE streaming responses, if an asynchronous callback event of LLM calling an external tool is detected, the callback data is received and the MCP context state is updated. Based on the updated context state, the model inference process is retried, and the results are pushed to the client as a new SSE message segment.

8. The method according to claim 1, characterized in that, Also includes: Record key operation logs throughout the entire conversion process, including request parameters, response content, rule mapping matching status, and exception information; Provides a visual monitoring interface to display log data and system operating status.

9. A computer-readable storage medium having a program stored thereon, characterized in that, When the program is executed by the processor, it implements the steps of the method as described in any one of claims 1-8.

10. An electronic device comprising a memory, a processor, and a program stored in the memory and executable on the processor, characterized in that, When the processor executes the program, it implements the steps of the method as described in any one of claims 1-8.

Citation Information

Cited By

  • Large-model cross-domain remote calling method and device for UDP (User Datagram Protocol) network

    CN121711377A