Method, system and device for issuing JAVA API as MCP server and medium

By extracting and mapping API interface metadata in JAVA applications and dynamically registering interfaces with the MCP server, the problems of low registration efficiency and schema deviation in existing technologies are solved. This enables efficient and accurate API publishing and real-time effect of changes, supporting the rapid integration of enterprise-level APIs into the intelligent agent ecosystem.

CN121193798APending Publication Date: 2025-12-23INSPUR GENERSOFT CO LTD

Patent Information

Application Number
CN202511714713.9
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2025-11-21
Publication Date
2025-12-23

AI Technical Summary

Technical Problem

Existing technologies for converting enterprise Java system RESTful APIs into MCP servers suffer from problems such as low registration efficiency, discrepancies between schema generation and code contracts, and the need to restart services for interface changes. They cannot support the batch conversion and dynamic deployment of enterprise-level APIs.

Method used

By scanning the registered request mappings in the Spring container of a Java application, extracting API interface metadata, generating a structured collection of ApiMetadata objects, and generating tool pattern definitions in batches based on type mapping rules, the API interfaces are dynamically registered with the MCP server without restarting the application.

Benefits of technology

It enables second-level batch publishing of JAVA API to the MCP server, and the dynamic registration mechanism ensures that API changes take effect in real time, improving system availability and iteration efficiency, and ensuring the accuracy of schema description and the success rate of agent invocation.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN121193798A_ABST
    Figure CN121193798A_ABST
Patent Text Reader

Abstract

The invention relates to the technical field of data processing, and particularly provides a method, a system, equipment and a medium for publishing JAVA API as an MCP server, and the method comprises the following steps: when a JAVA application runs, extracting metadata of all API interfaces by scanning registered request mapping in a Spring container of the JAVA application, and generating a structured ApiMetadata object set; generating a plurality of tool mode definitions conforming to a context protocol specification of a large language model in batches by using the ApiMetadata object set through a type mapping rule; on the basis of the tool mode definition, under the condition that a JAVA application does not need to be restarted, a corresponding API interface is dynamically registered to an MCP server, and the API interface can be configured to be found and called by a large language model in an intelligent agent. According to the method, second-level batch release from the JAVA API to the MCP tool is realized through non-intrusive scanning and automatic Schema generation.
Need to check novelty before this filing date? Find Prior Art

Description

TECHNICAL FIELD

[0001] The application belongs to the technical field of data processing, and particularly relates to a method, system, device and medium for publishing JAVA API as an MCP server. BACKGROUND

[0002] Currently, the existing JAVA system RESTful API of an enterprise is quickly converted into an MCP (Model-Context Protocol) server to integrate into the large language model agent ecosystem, mainly in three technical routes: SDK native implementation, gateway adaptation layer and framework annotation extension. However, these existing solutions all have significant defects, generally relying on developers to manually write annotations and Schema descriptions for each interface, resulting in extremely low registration efficiency and being unable to support batch conversion of enterprise-level APIs; at the same time, the generation of Schema and the actual contract of the code are prone to deviation, resulting in poor accuracy of agent calling; in addition, any change of the interface usually needs to restart the service to take effect, lacking dynamic publishing capability, which seriously hinders the rapid reuse and value release of the enterprise stock business capability in the agent era. SUMMARY

[0003] In view of the above deficiencies of the prior art, the application provides a method, system, device and medium for publishing JAVA API as an MCP server to solve the above technical problems.

[0004] In a first aspect, the application provides a method for publishing JAVA API as an MCP server, comprising: extracting metadata of all API interfaces by scanning registered request mappings in a Spring container of a JAVA application at runtime, and generating a structured ApiMetadata object set; generating a plurality of tool schema definitions conforming to the large language model context protocol specification in batches through type mapping rules based on the ApiMetadata object set; based on the tool schema definition, dynamically registering and publishing corresponding API interfaces to an MCP server without restarting the JAVA application, so that the API interfaces can be discovered and called by the large language model configured in the agent.

[0005] In an optional embodiment, at the runtime of the JAVA application, the metadata of all API interfaces is extracted by scanning the registered request mappings in the Spring container, including obtaining the RequestMappingHandlerMapping component through dependency injection after the Spring container is started; Traverse the Map<RequestMappingInfo, HandlerMethod> mapping maintained in the component; For each mapping entry, extract the request path and HTTP method from its RequestMappingInfo object, and get the corresponding Java method object, parameter information and return value type from its HandlerMethod object; Among them, the step of extracting parameter information specifically includes: Traverse the parameter list of the Java method object by reflection; If the parameter is annotated with @RequestBody, record the type of the parameter as a JSON object parameter; If the parameter is annotated with @RequestParam or @PathVariable, extract the parameter name, whether it is required, and the default value information specified in the annotation.

[0006] In an optional implementation, when traversing the mapping, a filtering step is further included: Determine whether the class to which the Java method object belongs is marked with the @RestController annotation, or is marked with both the @Controller and @ResponseBody annotations; Only when the determination result is yes, the subsequent metadata extraction operation is performed on the mapping entry.

[0007] In an optional implementation, a structured ApiMetadata object set is generated, including: Encapsulate the extracted interface metadata into a unified ApiMetadata object; wherein each ApiMetadata object contains at least the following fields: request path; HTTP method; implementation class name; method name; parameter list composed of multiple parameter objects, each parameter object containing parameter name, parameter type and whether it is required; return value type; interface description information; The parameter object in the parameter list has a parameter type of Java native type or custom object type.

[0008] In an optional implementation, the ApiMetadata object set is batch-generated into multiple tool schema definitions conforming to the context protocol specification of the large language model through a type mapping rule, including: According to a predefined Java type to JSON Schema type mapping rule, convert the parameter and return value types in the ApiMetadata object; According to the mandatory identification in the parameter information, a required field in the tool mode definition is generated; The Java method name is mapped to the name field of the tool mode definition, and the description field thereof is generated based on the interface description information; Wherein, for a complex object type, the field structure thereof is recursively parsed to generate nested properties; The Java type to JSON Schema type mapping rule includes: The String type in Java is mapped to the "string" type of the JSON Schema; The Integer, int, Long and long types in Java are mapped to the "integer" type of the JSON Schema; The Double, Float, double and float types in Java are mapped to the "number" type of the JSON Schema; The Boolean and boolean types in Java are mapped to the "boolean" type of the JSON Schema; The LocalDateTime type in Java is mapped to the "string" type of the JSON Schema, and the "date-time" format is attached; The List <t>The type is mapped to the "array" type of JSON Schema, and the generic parameter T is recursively processed to define its items attribute. The custom POJO object type in Java is mapped to the "object" type of JSON Schema, and its fields are recursively parsed to generate nested properties.

[0009] In an optional implementation, based on the tool mode definition, the corresponding API interface is dynamically registered and published to an MCP server without restarting the JAVA application, including: Listen to the change event of the tool mode definition, which is triggered by one of the following conditions: detecting that a new or updated Bean with the @RestController annotation is added or updated in the Spring container; receiving a manually submitted external API configuration through a management console; sensing the Spring container refresh caused by code hot deployment or classpath reloading; Register the new or updated tool mode definition to a local memory registry, wherein the local memory registry is implemented using a thread-safe data structure and supports multiple versions of tool mode definitions; In response to user operations, logically combine multiple API interface corresponding tool mode definitions into a business domain service; Push the registered or combined tool mode definition and its associated API interface metadata to a centralized service publishing center to complete the publication of the MCP service.

[0010] In an optional implementation, based on the tool mode definition, the corresponding API interface is dynamically registered and published to an MCP server without restarting the JAVA application, including: Listen to one or more event sources to trigger the publishing process, including: application lifecycle events, classpath change events, and manually triggered instructions received through a preset management endpoint; After the event is triggered, scan the toolkits declared in the application and extract their metadata; then filter the toolkits based on the preset publishing strategy, only add the toolkits with automatic publishing strategy to the publishing queue; the publishing strategy at least includes automatic publishing, manual publishing and gray publishing strategy; and the toolkit is declared at the class level through the @McpToolkit annotation; The tool package in the release queue is batch processed in units of tool packages, including: generating a unified and incremental version number for all interfaces in the tool package at one time, and batch generating the corresponding tool mode definition based on the version number; then, all tool mode definitions of the entire tool package are registered to the MCP server through an atomic operation; Wherein, the atomic operation refers to registering all tool mode definitions of the same tool package as a whole to the MCP server through one call or in one transactional session, to ensure the consistency of the version state.

[0011] In the second aspect, the application provides a system for publishing JAVA API to MCP server, comprising: The data acquisition module is configured to extract the metadata of all API interfaces and generate a structured ApiMetadata object set by scanning the registered request mapping in the Spring container of the JAVA application during the runtime of the JAVA application; The data mapping module is configured to batch generate a plurality of tool mode definitions conforming to the context protocol specification of the large language model by type mapping rules based on the ApiMetadata object set; The interface release module is configured to register and publish the corresponding API interface to a MCP server dynamically based on the tool mode definition without restarting the JAVA application, so that the API interface can be discovered and called by the large language model in the agent.

[0012] In the third aspect, a device is provided, comprising: The memory is configured to store a program for publishing JAVA API to MCP server; The processor is configured to implement the steps of the method for publishing JAVA API to MCP server when executing the program for publishing JAVA API to MCP server.

[0013] In the fourth aspect, a computer readable medium is provided, and the medium stores a program for publishing JAVA API to MCP server. The program for publishing JAVA API to MCP server is executed by the processor to implement the steps of the method for publishing JAVA API to MCP server provided in the first aspect.

[0014] The method, system, device and medium for publishing JAVA API for MCP server provided by the application have the advantages that the method for publishing JAVA API for MCP server provided by the application realizes the second-level batch publishing of JAVA API to MCP tools through non-invasive scanning and automatic Schema generation, reduces the man-hour level work required by traditional manual adaptation to the minute level, the dynamic registration mechanism ensures that API changes can take effect in real time without restarting the application, and greatly improves the system availability and iteration efficiency. Meanwhile, the automatic type mapping and version management fundamentally guarantee the accuracy of Schema description and significantly improve the success rate of agent calling, and provide an efficient and reliable technical path for the rapid integration of enterprise stock business capabilities into the agent ecology. BRIEF DESCRIPTION OF DRAWINGS

[0015] In order to more clearly illustrate the technical solutions in the embodiments of the application or the prior art, the following will briefly introduce the drawings needed to be used in the embodiments or the prior art description. Obviously, for those of ordinary skill in the art, other drawings can also be obtained based on these drawings without any creative effort.

[0016] Figure 1 is a schematic flowchart of the method of one embodiment of the application.

[0017] Figure 2 is a schematic block diagram of the system of one embodiment of the application.

[0018] Figure 3 is a structural schematic diagram of the device provided by the embodiment of the application. DETAILED DESCRIPTION

[0019] In order to make the technical personnel in the art better understand the technical solutions in the application, the technical solutions in the embodiments of the application will be described clearly and completely below with reference to the drawings in the embodiments of the application. Obviously, the described embodiments are only a part of the embodiments of the application, not all the embodiments. Based on the embodiments in the application, all other embodiments obtained by those of ordinary skill in the art without any creative effort should belong to the protection scope of the application.

[0020] Unless otherwise defined, all technical and scientific terms used herein have the same meaning as commonly understood by one of ordinary skill in the art to which the application belongs. The terms used in the specification of the application are only for the purpose of describing the specific embodiments and are not intended to limit the application.

[0021] The method for publishing JAVA API for MCP server provided by the embodiment of the application is executed by a computer device, and accordingly, the system for publishing JAVA API for MCP server runs in the computer device.

[0022] Figure 1 is a schematic flow chart of the method of one embodiment of the present application. In which, Figure 1 The execution subject can be a system that publishes JAVA API as a MCP server. According to different needs, the order of steps in the flow chart can be changed, and some can be omitted.

[0023] As Figure 1 shown, the method comprises: S1. In the JAVA application runtime, extract the metadata of all API interfaces by scanning the request mappings registered in its Spring container, and generate a structured ApiMetadata object set; S2. Batch generate a plurality of tool mode definitions conforming to the context protocol specification of the large language model based on the type mapping rule of the ApiMetadata object set; S3. Based on the tool mode definition, dynamically register and publish the corresponding API interface to a MCP server without restarting the JAVA application, so that the API interface can be discovered and called by the large language model in the intelligent agent.

[0024] In one embodiment of the present application, based on step S1, a possible embodiment will be given below to non-restrictively explain its specific implementation scheme.

[0025] S101. Component acquisition technology The instance of the RequestMappingHandlerMapping component is automatically obtained from the Spring application context through the @Autowired annotation of the Spring framework or the applicationContext.getBean() method in the ApplicationRunner implementation class. The component is automatically created by Spring MVC during the initialization process, and the handlerMethods attribute inside it maintains the complete request mapping table data structure.

[0026] S202. Mapping traversal technology The system traverses each mapping entry by handlerMethods.entrySet() through the Java collection iterator or enhanced for loop. For each Map.Entry<RequestMappingInfo, HandlerMethod> entry, access its getKey() and getValue() methods to obtain the mapping information object and processing method object, respectively.

[0027] S103. Annotation filtering technology The handlerMethod.getBeanType().isAnnotationPresent(RestController.class) method is called through the Java reflection mechanism to detect class-level annotations, or the isAnnotationPresent(Controller.class) and isAnnotationPresent(ResponseBody.class) methods are combined to perform double verification to ensure that only true RESTful endpoints are processed.

[0028] S104. Metadata extraction technology The getPatternsCondition().getPatterns() method is called from the RequestMappingInfo object to obtain the URL request pattern, and the getMethodsCondition().getMethods() method is called to obtain the supported HTTP methods. The getMethod() method is called from the HandlerMethod object to obtain the Java method object, and then the getDeclaringClass().getName() method is called to obtain the full class name, the getName() method is called to obtain the method name, and the Spring's GenericTypeResolver.resolveReturnType() method is called to parse the generic return type.

[0029] S105. Parameter parsing technology The parameter array is obtained through method.getParameters(), and each Parameter object is traversed to obtain the annotation array through getAnnotations(). Through instanceof checking or annotation type matching, annotations such as @RequestBody, @RequestParam, and @PathVariable are identified, and the name(), required(), and defaultValue() methods of the corresponding annotation objects are called to extract parameter metadata.

[0030] S106. Data structure encapsulation technology The ApiMetadata and ParameterMetadata entity classes are created, and the extracted metadata is encapsulated into object structures through constructors or the Builder pattern. The parameter list uses ArrayList <parametermetadata>In an implementation, a parameter set is dynamically constructed through an add() method to ensure structured storage of data and efficiency of subsequent processing.

[0031] Through the above specific technical means combination, the system realizes automatic and accurate extraction of complete metadata information of RESTful API from the Spring MVC framework, and lays a solid foundation for subsequent automatic processing.

[0032] In an embodiment of the present application, based on step S2, a possible embodiment will be given below to non-restrictively illustrate the specific implementation scheme.

[0033] S201. Method information processing mechanism The system establishes a method name mapping rule, and converts the Java method name into an underscore naming method or keeps the camel case format through string processing technology. For the acquisition of description information, the system reads the specific annotations (such as Swagger's @Operation or SpringDoc's @ApiOperation) declared on the method and class through Java reflection mechanism, and extracts the summary or description attribute values. When lacking explicit annotations, the system has a built-in method name dictionary, which automatically synthesizes natural language descriptions by matching common verbs (such as get, create, update) and nouns (such as user, order) in the method name.

[0034] S202. Type mapping technology implementation The system maintains a mapping table of Java types to JSON Schema types, which takes Java class name as key and corresponding JSON Schema type description as value. For basic data types, the system matches the fully qualified name of Java type with the predefined basic type list. For date and time types, the system recognizes the relevant classes under the java.time package and adds the format field as "date-time" to realize special processing.

[0035] S203. Complex type analysis technology The system uses a recursive descent analysis algorithm to process complex types. For collection types, the system analyzes the actual type of the generic parameter through the GenericTypeResolver tool of Java reflection API, and recursively calls the type mapping process. For POJO object types, the system obtains all serializable fields through the BeanDescription of Jackson library, and then recursively generates the corresponding JSON Schema attribute definition for each field.

[0036] S204. Mandatory field collection mechanism The system collects the parameter names marked as true in the required flag in the parameter metadata into an ArrayList, and finally converts it into a JSON array format as the value of the required field.

[0037] The Java type to JSON Schema type mapping rules include: Map the String type in Java to the "string" type in JSON Schema; Map the Integer, int, Long, and long types in Java to the "integer" type in JSON Schema; Map the Double, Float, double, and float types in Java to the "number" type in JSON Schema; Map the Boolean and boolean types in Java to the "boolean" type in JSON Schema; Map the LocalDateTime type in Java to the "string" type in JSON Schema, and append the "date-time" format; Map the List <t>Type maps to JSON Schema's "array" type and recursively processes generic argument T to define its items property; Custom POJO object type in Java is mapped to JSON Schema's "object" type and its fields are recursively parsed to generate nested properties.

[0038] In an embodiment of the present application, based on step S3, a possible embodiment will be given below to specifically illustrate the non-limiting embodiment.

[0039] S301. Event listening mechanism The system realizes the listening of change events through various technical means: For the change of Beans in the Spring container, the ApplicationListener interface is implemented to listen to the container refresh event, and the BeanPostProcessor is combined to post-process the Beans with the annotation of @RestController to identify them; For manual triggering, a RESTful management endpoint is exposed through the annotation of @RestController, a publish interface is mapped using @PostMapping, and JSON format configuration data is received; For hot deployment events, the hot restart detection mechanism of Spring Boot DevTools is integrated, or the class file timestamp change is monitored based on the Java Agent bytecode enhancement technology.

[0040] S302. Memory registry implementation The local memory registry uses ConcurrentHashMap<String, VersionedToolSchema> as the core storage structure, where the key is the tool schema definition identifier, and the value is the versioned schema definition wrapper object. Each VersionedToolSchema contains a version number, a creation timestamp, and actual schema definition content, and a history version chain is maintained through CopyOnWriteArrayList to ensure read-write concurrency safety.

[0041] S303. Service composition technology The system provides a web-based management interface, and realizes drag-and-drop combination operation through a Vue.js front-end framework. The back-end uses the composite pattern in the design pattern to create a CompositeMcpService class, which internally maintains a List collection and routes requests to specific API interfaces through a unified invoke method. The composite relationship is persisted to a MySQL database, and the transactionality of operations is guaranteed through @Transactional.

[0042] S304. Service publishing mechanism The publishing process is implemented using an asynchronous message queue, and the publishing tasks are distributed to multiple publishing nodes through the Topic Exchange of RabbitMQ. The publishing client sends a POST request to the service publishing center using OkHttp3, and the request body is JSON data that complies with the MCP protocol specification, containing complete tool mode definitions, metadata signatures, and version information. After verification by the service publishing center, the service information is updated to the Redis cache cluster, and a service discovery interface is provided for agents to query.

[0043] Step S3 in another embodiment, comprising: 1. Multi-source event listening mechanism, the system establishes a unified event listening bus, and captures different event sources in the following ways: Application lifecycle events: implement the ApplicationListener interface of Spring to listen to core events such as ContextRefreshedEvent and ApplicationReadyEvent; Classpath change event: integrate Spring Boot DevTools to monitor classpath changes through RestartEndpoint, or detect class redefinition based on Java Instrumentation API; Manual trigger interface: create a management endpoint using the @RestController annotation, use the HTTP POST method to receive trigger instructions, and use Spring Security for access permission control.

[0044] 2. Annotation-driven toolkit identification, the system defines the @McpToolkit meta-annotation, which contains serverName, version, and strategy attributes. Scan all classes with this annotation in the classpath using Spring's ClassPathScanningCandidateComponentProvider, and use AnnotationMetadata to parse annotation attribute values to build complete toolkit metadata.

[0045] 3. Strategy filtering engine, the system maintains a strategy library of enumeration type, including AUTO, MANUAL, GRAY three strategies. The filtering engine compares the strategy attribute in the toolkit annotation with the strategy configuration, and uses the strategy mode to realize different processing logic. Only the toolkit with AUTO strategy will be added to the LinkedBlockingQueue formed by the pending release queue.

[0046] 4. Versioned batch processing, the system uses a timestamp-based version number generation algorithm, with the format v{major version}.{minor version}.{timestamp}. The AtomicLong is used to ensure the uniqueness and incrementality of the version number. All interfaces in the same toolkit are uniformly assigned the version number to ensure version consistency.

[0047] 5. Atomic registration mechanism, atomic operation is realized through two technical solutions: Single call mode: serialize all tool mode definitions of the entire toolkit into a single JSON array, and submit it to the MCP server through a HTTP / 2 streaming request; Transaction session mode: based on database transactions or distributed transaction framework, register each tool mode definition in the transaction in turn, and perform overall rollback when any fails.

[0048] Through the systematic combination of the above technical means, the application realizes the complete automatic process from event awareness to service release, and ensures the reliability, consistency and efficiency of large-scale API release.

[0049] In some embodiments, the system of publishing JAVA API for MCP server can include a plurality of functional modules composed of computer program segments. The computer programs of each program segment in the system of publishing JAVA API for MCP server can be stored in the memory of the computer device and executed by at least one processor to perform the functions of publishing JAVA API for MCP server (see Figure 1 Description).

[0050] In this embodiment, the system of publishing JAVA API for MCP server can be divided into a plurality of functional modules according to the functions it performs, as shown in Figure 2 The module referred to in the application refers to a series of computer program segments that can be executed by at least one processor and can complete a fixed function, which are stored in the memory. In this embodiment, the functions of each module will be described in detail in subsequent embodiments.

[0051] The data acquisition module is configured to extract metadata of all API interfaces and generate a structured ApiMetadata object set when a JAVA application is running by scanning request mappings registered in a Spring container thereof; The data mapping module is configured to generate a plurality of tool mode definitions conforming to a context protocol specification of a large language model by type mapping rules based on the ApiMetadata object set; The interface publishing module is configured to register and publish corresponding API interfaces to an MCP server based on the tool mode definitions without restarting the JAVA application, so that the API interfaces can be discovered and called by the large language model in the intelligent agent.

[0052] Figure 3 The method for publishing JAVA API to an MCP server provided by the embodiments of the present application can be applied to a device. Those skilled in the art can understand that the device structure involved in the embodiments of the present application does not constitute a limitation on the device, and the device can include more or fewer components than the illustration, or combine certain components, or different component arrangements. In the embodiments of the present application, the device includes but is not limited to a laptop computer, a desktop computer, a workstation, a personal digital assistant, a server, a blade server, a mainframe computer, and other suitable computers. The device can also represent various forms of mobile devices, such as a personal digital processor, a cellular phone, a smart phone, a wearable device, and other similar computing devices. The components shown herein, their connections and relationships, and their functions are merely examples, and are not intended to limit the implementation of the embodiments of the present application described herein and / or claimed.

[0053] The device 300 can include a processor 310, a memory 320, and a communication unit 330. These components communicate through one or more buses. Those skilled in the art can understand that the structure of the server shown in the figure does not constitute a limitation on the present application, and it can be a bus structure or a star structure, and can include more or fewer components than the illustration, or combine certain components, or different component arrangements.

[0054] The memory 320 can be used to store the execution instructions of the processor 310, and the memory 320 can be implemented by any type of volatile or non-volatile storage device or a combination thereof, such as static random access memory (SRAM), electrically erasable programmable read-only memory (EEPROM), erasable programmable read-only memory (EPROM), programmable read-only memory (PROM), read-only memory (ROM), magnetic storage, flash memory, magnetic disk or optical disk. When the execution instructions in the memory 320 are executed by the processor 310, the device 300 can perform part or all of the steps in the following method embodiments.

[0055] The processor 310 is the control center of the storage device, connects various parts of the entire electronic device through various interfaces and lines, and performs various functions of the electronic device and / or processes data by running or executing software programs and / or modules stored in the memory 320 and calling data stored in the memory. The processor can be composed of an integrated circuit (IC), for example, can be composed of a single packaged IC, or can be composed of multiple packaged ICs connected together. For example, the processor 310 can only include a central processing unit (CPU). In the embodiments of the present application, the CPU can be a single operation core or can include multiple operation cores.

[0056] The communication unit 330 is used to establish a communication channel, so that the storage device can communicate with other devices. The communication unit 330 receives user data sent by other devices or sends user data to other devices.

[0057] The present application also provides a computer medium, wherein the computer medium can store a program, and the program can include part or all of the steps in the embodiments provided by the present application when executed. The medium can be a magnetic disk, an optical disk, a read-only memory (ROM) or a random access memory (RAM), etc.

[0058] Those skilled in the art can clearly understand that the technical solutions in the embodiments of the present application can be implemented by means of software plus necessary universal hardware platforms. Based on such an understanding, the technical solutions in the embodiments of the present application can be embodied in the form of a software product, which is stored in a medium such as a U disk, a mobile hard disk, a read-only memory (ROM), a random access memory (RAM), a magnetic disk or an optical disk, and includes a plurality of instructions for causing a computer device (which can be a personal computer, a server, or a second device, a network device, etc.) to execute all or part of the steps of the methods described in the various embodiments of the present application.

[0059] In the present specification, the same or similar parts among various embodiments can be referred to each other. Especially, for the device embodiments, since they are basically similar to the method embodiments, the description is relatively simple, and the relevant parts can be referred to the description in the method embodiments.

[0060] In the several embodiments provided in the present application, it should be understood that the disclosed system and method can be implemented in other ways. For example, the system embodiments described above are merely schematic. For example, the division of the modules is merely a logical function division. In actual implementation, another division manner can be used. For example, a plurality of modules or components can be combined or integrated into another system, or some features can be omitted or not executed. In addition, the coupling or direct coupling or communication connection between the displayed or discussed modules can be indirect coupling or communication connection through some interface, system or module, and can be electrical, mechanical or other forms.

[0061] The modules described as separate components can or can not be physically separated, and the components displayed as modules can or can not be physical modules, i.e. can be located in one place or distributed on a plurality of network modules. Some or all of the modules can be selected according to actual needs to achieve the purpose of the present embodiment.

[0062] In addition, each functional module in the various embodiments of the present application can be integrated in one processing module, or each module can exist physically independently, or two or more modules can be integrated in one module.

[0063] Although the present application has been described in detail with reference to the preferred embodiments, it should be understood that the application is not limited to those preferred embodiments. Various modifications and equivalents can be made by those skilled in the art without departing from the spirit and scope of the application. Any and all modifications and equivalents are intended to be included within the scope of the present application.< / t> < / parametermetadata> < / t>

Claims

1. A method for publishing a JAVA API as an MCP server, characterized in that, include: When a Java application is running, it scans the request mappings registered in its Spring container, extracts the metadata of all API interfaces, and generates a structured collection of ApiMetadata objects. The collection of ApiMetadata objects is used to generate multiple tool pattern definitions that conform to the Large Language Model Context Protocol specification in batches, based on type mapping rules. Based on the aforementioned tool pattern definition, without restarting the JAVA application, the corresponding API interface is dynamically registered with an MCP server and published, enabling the API interface to be discovered and invoked by the large language model configured in the agent.

2. The method according to claim 1, characterized in that, During Java application runtime, metadata for all API interfaces is extracted by scanning the registered request mappings in its Spring container, including... After the Spring container starts up, the RequestMappingHandlerMapping component is obtained through dependency injection; Iterate through the Map maintained in this component<RequestMappingInfo, HandlerMethod> Mapping relationship; For each mapping entry, extract the request path and HTTP method from its RequestMappingInfo object, and obtain the corresponding Java method object, parameter information and return value type from its HandlerMethod object; The steps for extracting parameter information specifically include: Iterate through the parameter list of the Java method object using reflection; If a parameter is annotated with @RequestBody, the type of that parameter will be recorded as a JSON object parameter; If a parameter is annotated with @RequestParam or @PathVariable, then extract the parameter name, whether it is required, and the default value information specified in the annotation.

3. The method according to claim 2, characterized in that, The process of traversing the mapping relationship also includes a filtering step: Determine whether the class to which the Java method object belongs is annotated with @RestController, or whether it is annotated with both @Controller and @ResponseBody; Subsequent metadata extraction operations are only performed on the mapped entry if the judgment result is yes.

4. The method according to claim 1, characterized in that, Generate a structured collection of ApiMetadata objects, including: The extracted interface metadata is encapsulated into a unified ApiMetadata object; each ApiMetadata object contains at least the following fields: request path; HTTP method; implementation class name; method name; a parameter list consisting of multiple parameter objects, each parameter object containing a parameter name, parameter type, and an indicator of whether it is required; return value type; and interface description information. The parameter objects in the parameter list are of Java native types or custom object types.

5. The method according to claim 1, characterized in that, The collection of ApiMetadata objects is used to generate multiple tool pattern definitions conforming to the Large Language Model Context Protocol specification in batches, based on type mapping rules. These definitions include: Based on a predefined Java type to JSON Schema type mapping rule, the parameter and return value types in the ApiMetadata object are converted; Based on the required field identifier in the parameter information, generate the required field in the tool pattern definition; Map Java method names to the name field defined in the utility pattern, and generate their description field based on the interface description information; For complex object types, their field structure is recursively parsed to generate nested properties; The Java type to JSON Schema type mapping rules include: Map the Java String type to the JSON Schema "string" type; Map the Java Integer, int, Long, and long types to the "integer" type in JSON Schema; Map the Double, Float, double, and float types in Java to the "number" type in JSON Schema; Map the Boolean and boolean type in Java to the "boolean" type in JSON Schema; Map the LocalDateTime type in Java to the "string" type in JSON Schema, and append the "date-time" format; List in Java <t> The type is mapped to the "array" type in JSON Schema, and the generic parameter T is processed recursively to define its items property;< / t> Maps custom POJO object types in Java to the "object" type in JSON Schema and recursively parses their fields to generate nested properties.

6. The method according to claim 1, characterized in that, Based on the aforementioned tool pattern definition, without restarting the Java application, the corresponding API interfaces are dynamically registered with and published to an MCP server, including: Listen for change events defined by the utility pattern, which are triggered by one of the following conditions: a new or updated bean annotated with @RestController is detected in the Spring container; a manually committed external API configuration is received through an administration console; or a Spring container refresh is detected due to hot code deployment or classpath reloading. Register new or updated utility pattern definitions to a local memory registry, which is implemented using thread-safe data structures and supports the coexistence of multiple versions of utility pattern definitions; In response to user actions, the tool pattern definitions corresponding to multiple API interfaces are logically combined into a business domain service; The registered or combined tool pattern definitions and their associated API interface metadata are pushed to a centralized service publishing center to complete the publishing of MCP services.

7. The method according to claim 1, characterized in that, Based on the aforementioned tool pattern definition, without restarting the Java application, the corresponding API interfaces are dynamically registered with and published to an MCP server, including: Listen to one or more event sources to trigger the release process. The event sources include: application lifecycle events, classpath change events, and manual trigger commands received through a preset management endpoint. After the event is triggered, the toolkits declared in the application are scanned and their metadata is extracted; then the toolkits are filtered based on a preset release strategy, and only toolkits with an automatic release strategy are added to the release queue; the release strategy includes at least automatic release, manual release and canary release strategies; and the toolkits are declared at the class level using the @McpToolkit annotation; For toolkits in the release queue, batch processing is performed on a toolkit-by-toolkit basis, including: generating a uniform, incremental version number for all interfaces in the toolkit at once, and generating the corresponding tool pattern definitions in batches based on this version number; then, registering all tool pattern definitions of the entire toolkit to the MCP server through atomic operations. In this context, atomic operation refers to registering all tool pattern definitions of the same toolkit as a whole with the MCP server through a single call or within a transactional session to ensure the consistency of version status.

8. A system that publishes a JAVA API as an MCP server, characterized in that, include: The data acquisition module is used to extract metadata of all API interfaces and generate a structured collection of ApiMetadata objects by scanning the registered request mappings in the Spring container when a JAVA application is running. The data mapping module is used to generate multiple tool pattern definitions that conform to the Large Language Model Context Protocol specification in batches from the collection of ApiMetadata objects through type mapping rules. The interface publishing module is used to dynamically register and publish the corresponding API interface to an MCP server without restarting the JAVA application, based on the tool pattern definition, so that the API interface can be discovered and invoked by the large language model configured in the agent.

9. A device that publishes a JAVA API as an MCP server, characterized in that, include: Storage, used to store programs that publish JAVA API as an MCP server; A processor, configured to implement the steps of the method for publishing a Java API as an MCP server as described in any one of claims 1-7, when executing the program that publishes the Java API as an MCP server.

10. A computer-readable medium storing a computer program, characterized in that, The readable medium stores a program that publishes a JAVA API as an MCP server, and when the program that publishes a JAVA API as an MCP server is executed by a processor, it implements the steps of the method for publishing a JAVA API as an MCP server as described in any one of claims 1-7.

Citation Information

Patent Citations

  • Method and system for dynamically calling Java statistical analysis interface based on LLM and MCP

    CN120560800A

  • Application program interface calling method and device, equipment, storage medium and program

    CN120832253A

  • Semantic interface for publishing a web service to and discovering a web service from a web service registry

    US20070168479A1

Cited By

  • Data processing method and device, electronic equipment, storage medium and program product

    CN122132466A