A cross-platform tool invocation method and system based on MCP protocol
By generating kernel function call sequences in kernel mode, the construction and parsing of shell command text are avoided, thus solving the latency and security issues of the MCP server and achieving low-latency and secure tool calls.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- CHINA UNICOM DIGITAL TECNOLOGY CO LTD
- Filing Date
- 2026-05-13
- Publication Date
- 2026-06-09
AI Technical Summary
Existing MCP servers suffer from high end-to-end processing latency and high risk of command injection when handling tool call requests, making it difficult to meet the needs of sub-microsecond low-latency scenarios such as industrial real-time control.
By using eBPF programs to generate kernel function call sequences in kernel mode, the kernel native functions corresponding to the operation intent are executed directly, avoiding the construction and parsing of shell command text. Combined with multi-layer security checks, this ensures that the execution is carried out in kernel mode and the results are returned.
It achieves sub-microsecond end-to-end processing latency while eliminating command injection risks, thus improving system security and efficiency.
Smart Images

Figure CN122179465A_ABST
Abstract
Description
Technical Field
[0001] This invention belongs to the fields of operating system kernel technology, cross-platform communication technology and network security technology, and in particular relates to a cross-platform tool invocation method and system based on the MCP protocol. Background Technology
[0002] Existing MCP (Model Context Protocol) servers all employ a user-space architecture: the server listens for client connections via sockets in user space, copies received network packets from kernel space to user space, performs protocol parsing, generates corresponding shell executable command text based on the target operating system type, and finally creates a child process to execute the command text and capture the output. This implementation has the following drawbacks: a single request processing involves multiple stages, including copying network packets from kernel space to user space, user-space protocol parsing, child process creation, and command parsing and execution, resulting in high end-to-end processing latency, which cannot meet the needs of sub-microsecond low-latency scenarios such as industrial real-time control; furthermore, since the user-space program directly generates and executes shell command text, command injection protection relies on external methods such as parameter escaping, resulting in a large attack surface. Therefore, how to achieve extremely low latency in request processing while eliminating command injection risks from the execution mechanism has become a pressing technical problem in this field. Summary of the Invention
[0003] This application provides a cross-platform tool invocation method and system based on the MCP protocol. When the MCP server processes tool invocation requests, it can achieve sub-microsecond-level extremely low latency in request processing and eliminate the risk of command injection from the execution mechanism level.
[0004] This application discloses a cross-platform tool invocation method based on the MCP protocol, including: Receive tool invocation requests sent by the MCP client and parse them to obtain the tool name and invocation parameters; The tool name is mapped to a predefined operation intent. Based on the operation intent and the call parameters, and according to the attribute information of the target operating system corresponding to the tool call request, a kernel function call sequence for direct execution in kernel mode is generated by the eBPF program mounted to the kernel. During the generation of the kernel function call sequence, multi-layer security checks are performed. After the checks pass, the kernel function call sequence is executed, and the execution result is encapsulated according to the MCP protocol specification and returned to the MCP client.
[0005] Optionally, the generation of the kernel function call sequence for direct execution in kernel mode by the eBPF program mounted to the kernel includes: After mapping the tool name to a predefined operation intent, the memory address and calling convention of the kernel native function corresponding to the operation intent are retrieved through kernel BTF information; Based on the calling parameters and the calling conventions of the kernel native functions, input parameter verification rules are generated; The eBPF program securely binds the operational intent to the kernel native function, generating a kernel function call sequence for direct execution in kernel mode.
[0006] Optionally, the step of securely binding the operation intent with the kernel native function through the eBPF program to generate a kernel function call sequence for direct execution in kernel mode includes: The operation intent is decomposed into multiple atomic execution steps, each atomic execution step corresponds to an independent eBPF subroutine, and all eBPF subroutines are preloaded into the eBPF program array; The multiple atomic execution steps are stored in the kernel-state queue storage structure in the order of execution. The eBPF tail call jumps sequentially to the corresponding eBPF subroutine in the execution order, generating the kernel function call sequence consisting of the multiple atomic execution steps.
[0007] Optionally, performing multi-layer security checks during the generation of the kernel function call sequence includes: During the MCP protocol payload parsing process, the format verification, length verification, and whitelist verification of the calling parameters are performed synchronously. If the verification fails, the processing is terminated. During the process of binding the operation intent with the kernel native function, operation permission verification, operation scope verification, and risk level verification are performed simultaneously. If the verification fails, the process is terminated. Before executing the kernel function call sequence, a mandatory access control check is performed via an eBPF LSM hook so that the kernel function call sequence can be executed in the kernel-mode eBPF security sandbox after the check passes.
[0008] Optionally, before executing the kernel function call sequence, the following may also be included: Bind the TCP connection information of the MCP client with the generated session identifier to obtain the session identifier information; Session information is obtained based on the identifier of a single tool call request, the operation intent, the execution status, and the context data; The session identifier information and the session information are stored in a kernel-mode key-value storage structure.
[0009] Optionally, mapping tool names to predefined operational intents includes: The tool name is associated with the corresponding operation intention through a predefined mapping table. The mapping table stores the correspondence between tool name and operation intention, as well as the parameter constraint rules for each operation intention. After matching the corresponding operation intent, the format of the call parameters is validated according to the parameter constraint rules.
[0010] Optionally, the step of encapsulating the execution result according to the MCP protocol specification and returning it to the MCP client includes: The execution results are converted into structured data that conforms to the MCP specification; The structured data is populated into the response message, which includes a protocol version field, a request identifier field, and an execution result field. The encapsulated response message is sent to the MCP client via a TCP connection.
[0011] Optionally, the step of receiving a tool invocation request sent by the MCP client and parsing it to obtain the tool name and invocation parameters includes: The eBPF program, mounted to the kernel network hook point, receives network packets from the MCP client in kernel mode. In kernel mode, TCP stream reassembly is performed on the network packets to extract the MCP protocol payload; The tool name and calling parameters are obtained by zero-copy parsing of the MCP protocol payload.
[0012] Optionally, the step of performing zero-copy parsing of the MCP protocol payload to obtain the tool name and calling parameters includes: Based on the raw message pointer of the kernel socket buffer, the core fields of the MCP protocol payload are located through a pre-compiled fixed-offset finite state machine; The format and length of the core fields are validated synchronously. If the validation fails, the parsing is terminated and an error response is generated. Extract the tool name and calling parameters from the core fields that have passed the verification.
[0013] This application also discloses an operating system configured to receive tool invocation requests sent by an MCP client, parse the tool name and invocation parameters, map the tool name to a predefined operation intent, and, based on the operation intent and invocation parameters and the attribute information of the target operating system corresponding to the tool invocation request, generate a kernel function call sequence for direct execution in kernel mode through an eBPF program mounted to the kernel; perform multi-layer security checks during the generation of the kernel function call sequence, execute the kernel function call sequence after the checks pass, and encapsulate the execution result according to the MCP protocol specification and return it to the MCP client.
[0014] As can be seen from the above technical solution, after receiving and parsing the tool call request sent by the MCP client, the tool name is mapped to a predefined operation intent. Then, through the eBPF program mounted to the kernel, a kernel function call sequence for direct execution in kernel mode is generated based on the operation intent, call parameters, and attribute information of the target operating system. Since the generation process of the kernel function call sequence does not require constructing and concatenating shell command text, but directly retrieves the address and calling specification of the kernel native function corresponding to the operation intent through kernel BTF information, and directly binds the call parameters as input parameters of the kernel native function according to the function signature requirements, the entry point for command injection attacks is completely eliminated from the execution mechanism. Even if the call parameters contain special characters or shell metacharacters constructed by the attack, they cannot be executed by any shell parser because there is no shell parsing link in the entire execution chain. After performing multi-layer security checks on the kernel function call sequence, the kernel function call sequence is executed directly in kernel mode. The execution process does not require the creation of user-mode child processes, avoiding the system overhead of process creation and context switching from kernel mode to user mode. The execution result is directly encapsulated in kernel mode according to the MCP protocol specification and returned to the client through the kernel network path. This eliminates the overhead of multiple data copies and context switching between user mode and kernel mode, thereby achieving sub-microsecond end-to-end processing latency while eliminating the risk of command injection. Attached Figure Description
[0015] To more clearly illustrate the technical solutions in the embodiments of this application or the prior art, the drawings used in the description of the embodiments or the prior art will be briefly introduced below. Obviously, the drawings described below are some embodiments of this application. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort.
[0016] Figure 1 This is a flowchart illustrating a cross-platform tool invocation method based on the MCP protocol in an embodiment of this application; Figure 2 This is a schematic diagram of the process of generating a kernel function call sequence in a cross-platform tool calling method S200 based on the MCP protocol in an embodiment of this application; Figure 3 This is a flowchart illustrating S230, a cross-platform tool invocation method based on the MCP protocol, in an embodiment of this application. Figure 4 This is a flowchart illustrating a cross-platform tool invocation method S300 based on the MCP protocol in an embodiment of this application. Figure 5This is a flowchart illustrating S400-S600 of a cross-platform tool invocation method based on the MCP protocol in an embodiment of this application. Figure 6 This is a schematic diagram of the operation intent mapping process of a cross-platform tool invocation method S200 based on the MCP protocol in an embodiment of this application; Figure 7 This is a schematic diagram of the execution result encapsulation of a cross-platform tool invocation method S300 based on the MCP protocol in an embodiment of this application; Figure 8 This is a flowchart illustrating a cross-platform tool invocation method S100 based on the MCP protocol in an embodiment of this application. Figure 9 This is a flowchart illustrating S130, a cross-platform tool invocation method based on the MCP protocol, in an embodiment of this application. Detailed Implementation
[0017] In the following description, specific details such as particular system architectures and techniques are set forth for illustrative purposes and not for limitation, in order to provide a thorough understanding of the embodiments of this application. However, those skilled in the art will understand that this application may also be implemented in other embodiments without such specific details. In other instances, detailed descriptions of well-known systems, apparatuses, circuits, and methods are omitted so as not to obscure the description of this application with unnecessary detail.
[0018] In existing technologies, MCP (Model Context Protocol) is a standardized communication protocol for AI models to interact with external tools. Taking the implementation of a file list query function as an example, the existing server deploys a complete protocol processing program in user space, listening for TCP (Transmission Control Protocol) connections from clients via user-space sockets. When a client sends a tool invocation request, the server receives network packets in user space via the `recv` system call. This process requires copying network packet data from the socket buffer in kernel space to the application buffer in user space. The server then performs protocol parsing on the received data in user space, extracting the tool name and invocation parameters, and constructing the corresponding Shell command text based on the target operating system type. For example, in a Linux system, it constructs the command text `ls -la / home / user / documents`. The server then calls the `fork` system call to create a child process. Within this child process, the `exec` series of system calls executes the shell command interpreter. The shell interpreter performs lexical and syntactic analysis on the command text before executing the corresponding system calls. After execution, the server captures the child process's standard output and standard error output via a pipe or temporary file. The server then parses and structures the output, encapsulates it into a response message according to the MCP protocol specification, and sends the response message back to the client via the `send` system call. In this implementation, processing a single tool call request requires at least two context switches between user mode and kernel mode caused by system calls: a data copy from kernel mode to user mode when receiving a message, a data copy from user mode to kernel mode when sending a response, and a context switch during child process creation and exit. Meanwhile, the construction of command text relies on parameter escaping functions to escape shell metacharacters in user input. For example, this involves adding escape characters or enclosing characters like semicolons, pipes, backticks, and spaces. However, the correctness of the escaping logic depends on the developers' complete understanding of the shell syntax rules for each platform. The escaping implementations in the adaptation code of different tools may differ, and omissions or incomplete escaping rules can lead to command injection attacks. Furthermore, the shell interpreter's parsing and execution of the command text itself consumes CPU time, including steps such as lexical analysis, syntax tree construction, and built-in command lookup. Based on the above analysis, existing user-space MCP server implementations suffer from high end-to-end processing latency and a large command injection attack surface, making it difficult to simultaneously meet the needs of low-latency scenarios and execution security requirements.
[0019] Based on this, embodiments of this application provide a cross-platform tool invocation method based on the MCP protocol, such as... Figure 1 As shown, it includes: S100: Receives tool invocation requests sent by the MCP client and parses them to obtain the tool name and invocation parameters; S200: Map the tool name to a predefined operation intent, and based on the operation intent and the calling parameters, generate a kernel function call sequence for direct execution in kernel mode through the eBPF program mounted to the kernel, based on the attribute information of the target operating system corresponding to the tool call request; S300: Perform multi-layer security checks during the generation of the kernel function call sequence. After the checks pass, execute the kernel function call sequence and encapsulate the execution result according to the MCP protocol specification before returning it to the MCP client.
[0020] After receiving and parsing the tool invocation request sent by the MCP client, this application maps the tool name to a predefined operation intent. Then, through the eBPF (Extended Berkeley Packet Filter) program mounted to the kernel, it generates a kernel function call sequence for direct execution in kernel mode based on the operation intent, call parameters, and the target operating system's attribute information. Since the generation process of the kernel function call sequence does not require constructing and concatenating shell command text, but instead directly retrieves the address and calling specification of the kernel native function corresponding to the operation intent through kernel BTF (BPF Type Format) information, and directly binds the call parameters to the input parameters of the kernel native function according to function signature requirements, it completely eliminates the entry point for command injection attacks from the execution mechanism perspective. Even if the call parameters contain special characters or shell metacharacters constructed by the attack, they cannot be executed by any shell parser because there is no shell parsing stage in the entire execution chain. After performing multi-layer security checks on the kernel function call sequence, the kernel function call sequence is executed directly in kernel mode. The execution process does not require the creation of user-mode child processes, avoiding the system overhead of process creation and context switching from kernel mode to user mode. The execution result is directly encapsulated in kernel mode according to the MCP protocol specification and returned to the client through the kernel network path. This eliminates the overhead of multiple data copies and context switching between user mode and kernel mode, thereby achieving sub-microsecond end-to-end processing latency while eliminating the risk of command injection.
[0021] In this embodiment, the MCP client can be a large language model application that supports the MCP specification, an AI agent program, or other terminal program that needs to call operating system capabilities. The MCP client and server communicate via a TCP connection, and the communication protocol follows the MCP specification.
[0022] In this specific example, the tool invocation request is encapsulated according to the JSON RPC 2.0 (JSON Remote Procedure Call 2.0) protocol specification. JSON RPC 2.0 is a lightweight remote procedure call protocol that uses JSON format to encode request and response messages. The message structure of the tool invocation request includes four core fields: jsonrpc, id, method, and params. The jsonrpc field identifies the protocol version and its value is fixed as the string "2.0". The id field associates the request and response; it is generated by the client and can be a number or string. The server returns this field value verbatim in the response message so that the client can match the response with the pending request. The method field identifies the name of the method being invoked; in the tool invocation scenario, it takes the value "tools / call". The params field is an object type containing the tool name and invocation parameters. The tool name identifies the specific operating system capability that the client needs to invoke, and the invocation parameters are the input data required to execute the corresponding operating system capability.
[0023] For example, a complete tool invocation request message might contain the following: the jsonrpc field has a value of 2.0, the id field has a value of 1001, the method field has a value of tools / call, the params field is a nested JSON object containing a name subfield with a value of list_directory, and the arguments subfield is another nested JSON object containing a path subfield with a value of / home / user / documents. This request message indicates that the client is requesting to invoke the tool named list_directory, and is passing the path parameter / home / user / documents.
[0024] The process of receiving tool call requests from MCP clients can be implemented through user-space socket listening. Specifically, the server creates a TCP socket in user space and binds it to a specified port, then calls the `listen` system call to enter listening mode. When a client initiates a TCP connection request, the server calls the `accept` system call to accept the connection. After establishing the TCP connection, it uses the `recv` system call to receive packet data sent by the client. Alternatively, the server can also receive requests through kernel-space network hook programs. This involves using an eBPF program mounted to a kernel network hook point to directly capture network packets in kernel mode.
[0025] eBPF refers to Extended Berkeley Packet Filter, a technical framework for securely executing user-defined programs in kernel mode. Before being loaded into the kernel, eBPF programs must undergo static security verification by the kernel eBPF verifier. The verification includes checking for risks such as infinite loops, out-of-bounds memory access, and illegal kernel function calls. Only eBPF programs that pass the verifier's verification can be loaded and attached to kernel hook points for execution.
[0026] In the specific example above, the process of parsing a tool call request involves extracting fields and validating the format of a message conforming to the JSON RPC 2.0 specification. During parsing, the `jsonrpc` field value is first checked to ensure it is 2.0, confirming the message conforms to the JSON RPC 2.0 protocol version. Next, the `id` field is checked to ensure the request has a valid identifier. Then, the value of the `method` field is extracted to confirm the request type is `tools / call`, i.e., a tool call request. Finally, the tool name and call parameters are extracted from the `params` field. If, during the validation process, the `jsonrpc` field value is not 2.0, the `id` field is missing, the `method` field value is not as expected, or the `params` field format is invalid, parsing is terminated, and an error response message containing the error type, error code, and error description is generated and returned to the client.
[0027] The tool name is an identifier used by the client to specify the operating system capability to be invoked. For example, `list_directory` indicates directory content query, `read_file` indicates file content reading, and `get_process_list` indicates process list query. The call parameters are the input data required to execute the corresponding operating system capability. For example, a directory content query requires the path string of the target directory as a call parameter, a file content reading requires the file path string as a call parameter, and a process list query may not require any call parameters or may require filtering conditions as call parameters.
[0028] Operation intents are predefined, high-level semantic abstractions of the underlying operating system's capabilities. Each operation intent corresponds to a semantically clear operation description. For example, directory content query corresponds to retrieving a list of files and subdirectories in a specified directory; file content reading corresponds to retrieving the complete text content of a specified file; and process list query corresponds to retrieving information about currently running processes in the system. The same operation intent may correspond to different underlying implementations on different operating systems. For example, directory content querying in Linux can be done by calling the `getdents64` system call, in Windows by calling the `NtQueryDirectoryFile` kernel function, and on macOS by calling the `getdirentries64` system call. This semantic abstraction of operation intents allows MCP clients to invoke operating system capabilities without needing to concern themselves with the specific command syntax and system call interface differences of the underlying operating system; they only need to use a unified tool name.
[0029] The process of mapping tool names to predefined operation intents can be implemented using a predefined mapping table. The mapping table is a data structure that stores the correspondence between tool names and operation intents, as well as the parameter constraint rules for each operation intent. The mapping table can be loaded from a configuration file when the server starts, or it can be dynamically updated during server operation. For example, the mapping table stores the correspondence between `list_directory` and the directory content query operation intent, `read_file` and the file content read operation intent, and `get_process_list` and the process list query operation intent. Each operation intent is associated with parameter constraint rules, which define the constraints on the name, type, whether it is required, its value range, maximum length, and legal character set of the call parameters required by the operation intent. During the mapping matching process, after finding the corresponding operation intent in the mapping table based on the tool name, the call parameters are format-validated according to the parameter constraint rules associated with that operation intent. If the validation passes, the operation intent identifier and the validated call parameters are passed to subsequent steps.
[0030] The target operating system's attribute information includes the operating system type, major and minor version numbers, CPU hardware architecture, kernel version, and available system call interface information. The operating system type identifies the type of operating system, such as Linux. The operating system version number distinguishes different versions within the same operating system family, as the available kernel function interfaces may differ between different kernel versions. The CPU hardware architecture distinguishes different processor architectures, such as x86_64, ARM64, and RISC-V, because the kernel function calling conventions may differ between these architectures. The kernel version information determines the specific version number of the current kernel, allowing the retrieval of the calling conventions of native kernel functions matching the current kernel version from the kernel BTF information.
[0031] The eBPF program, mounted to the kernel, generates a sequence of kernel function calls for direct execution in kernel mode. This sequence of kernel function calls is a set of sequentially executed native kernel function calls orchestrated by the eBPF program. The kernel function call sequence executes directly in kernel mode without creating user-mode child processes or going through the generation and parsing of shell command text. The eBPF program runs in the kernel-mode eBPF virtual machine and is subject to the security constraints of the eBPF verifier, allowing it to execute only predefined, legal operations.
[0032] After mapping tool names to predefined operation intentions, the memory address and calling convention of the corresponding kernel native function are retrieved through kernel BTF information. BTF refers to BPF type format, which is metadata generated during kernel compilation containing information about kernel function and data structure types. It can be loaded into kernel space via BPF system calls for eBPF programs to query. BTF information contains type definitions for all functions and data structures in the kernel, including function names, the function's starting address in memory, the type and size of each input parameter, and the return type. Information about static functions not exported from the kernel can be retrieved through BTF information, eliminating the need to hardcode function memory addresses in the eBPF program code and achieving cross-kernel version compatibility. During the retrieval process, leveraging the CO-RE (Compile Once-Run Everywhere) feature of eBPF programs, the user-mode loader relocates the BTF relocation entries in the eBPF program bytecode based on the BTF information of the currently running kernel, resolving function names to actual memory addresses and calling convention information, and generating corresponding function call wrapper logic.
[0033] For example, the intent of directory content querying can be correlated with the kernel native functions `dentry_open` and `iterate_dir`. The `dentry_open` function opens the corresponding directory file based on a given path string, returning a pointer to a `file` structure. This structure represents an open file instance in the kernel, containing fields such as the file's inode information, a pointer to the file operation function table, and the file position offset. The `iterate_dir` function iterates through all directory entries in the directory corresponding to the given `file` structure pointer. For each directory entry read, a callback function is called for processing. Directory entries contain information such as the file or subdirectory name, inode number, and file type. Kernel BTF information reveals that the `dentry_open` function takes a pointer to a path string, a set of open flags, and a file permission mode value as input parameters, and returns a `file` structure pointer or an error code. The `iterate_dir` function takes a `file` structure pointer and a directory context structure pointer as input parameters, and returns an integer error code.
[0034] Input parameter validation rules are a set of validation logic executed in an eBPF program to ensure that input parameters passed to kernel native functions fully comply with the function calling conventions, preventing illegal input parameters from causing kernel function execution exceptions or memory safety issues. Input parameter validation rules include parameter type validation, value range validation, pointer address validity validation, and length validation. Type validation confirms that the data type of the called parameter matches the expected type of the kernel native function's input parameter; for example, path parameters should be of string type. Value range validation confirms that the value of the called parameter is within the range allowed by the kernel native function; for example, enable flags must be one of the predefined valid flag combinations. Pointer address validity validation confirms that the passed pointer address is within the valid address space accessible by the kernel, preventing null pointers or dangling pointers from causing kernel crashes. Length validation confirms that the length of string-type parameters does not exceed the maximum length allowed by the kernel; for example, the length of a path string does not exceed the PATH_MAX value specified by the file system.
[0035] For example, the input parameters of the dentry_open function include a path string pointer, open flags, and permission mode. The resulting input parameter validation rules include: path string length validation, ensuring the path string length does not exceed 4096 bytes and the string ends with a null character; valid character set validation, ensuring the path string does not contain control characters other than null bytes; pointer address validity validation, ensuring the address pointed to by the path string pointer is within the valid range of the kernel address space; and open flag validation, ensuring the open flags belong to a predefined valid combination.
[0036] The process of securely binding operation intentions with kernel native functions through eBPF programs involves associating the semantics of the operation intention with the execution logic of the kernel native function, binding the input parameter verification rules with the function call logic, and generating a complete kernel function call sequence. During the binding process, the eBPF program first extracts the specific values from the call parameters, verifies each parameter according to the input parameter verification rules, and sets the parameter values to the corresponding registers or stack locations according to the kernel native function calling specifications. Then, it initiates the kernel native function call through eBPF auxiliary functions such as `bpf_probe_read_kernel` or by directly calling instructions. The generated kernel function call sequence is logically equivalent to the shell command sequence constructed and executed in user space in traditional schemes, but the execution method is completely different: the kernel function call sequence does not go through any shell parsing stage; the execution steps corresponding to each operation intention are directly completed by the kernel native function calls arranged by the eBPF program, and the execution process is completed in a closed loop within kernel space. The generated function call sequence will undergo static security verification by the eBPF verifier. The verification includes checking whether the input parameter types of the function call match, whether there is unauthorized memory access, and whether there are illegal pointer operations. Only after the verification is passed can it be executed in kernel mode.
[0037] The kernel function call sequence generation process involves multi-layered security checks distributed across different stages of the request processing flow. If a check fails, the current request processing flow is terminated and the corresponding error message is returned. If the check passes, the kernel function call sequence is executed. Execution is completed in kernel mode, without creating a user-mode child process or entering kernel mode via a system call soft interrupt. During execution, the return values of native kernel functions are captured by the eBPF program. These return values include a pointer or value to the output data upon success and an error code upon failure. After obtaining the execution results, they are converted into structured data conforming to the MCP specification. Taking directory content query as an example, the execution results may include the filename, file size, file permissions, file owner information, and last modification time for each file in the directory. This information is organized according to a predefined structured field format.
[0038] Structured data is populated into the JSON RPC 2.0 response message, which includes the jsonrpc field, id field, and result or error field. The jsonrpc field value is consistent with the request message, set to 2.0. The id field value is consistent with the corresponding id field value in the request message, used by the client to match the response with the request. If the kernel function call sequence executes successfully, the result field contains structured execution result data; if execution fails, the error field contains an error object, which includes the error code, error type, and error description. The encapsulated response message is then sent to the MCP client via a TCP connection, completing the entire process of a tool call request.
[0039] In alternative implementations, such as Figure 2 As shown, the S200 generates a sequence of kernel function calls for direct execution in kernel mode via an eBPF program mounted to the kernel, including: S210: After mapping the tool name to a predefined operation intent, retrieve the memory address and calling convention of the kernel native function corresponding to the operation intent through kernel BTF information.
[0040] S220: Generate input parameter verification rules based on the calling parameters and the calling specifications of the kernel native functions.
[0041] S230: Securely bind the operation intent to the kernel native function through the eBPF program, and generate a kernel function call sequence for direct execution in kernel mode.
[0042] In this embodiment, the process of retrieving the memory address and calling convention of the kernel native function corresponding to the operation intent through kernel BTF information is completed during eBPF program loading. The eBPF program can use the CO-RE mechanism provided by the libbpf library for BTF relocation. When writing the eBPF program source code, the BPF_CORE_READ macro or the bpf_core_read series of helper functions are used to mark the field offsets and function addresses that need to be relocated from the BTF information. After compiling and generating the eBPF bytecode, when loaded on the target kernel, the libbpf loader automatically reads the BTF information of the currently running kernel and resolves the relocation entries in the eBPF bytecode into actual memory offsets and function addresses according to the type definitions in the BTF information. This mechanism allows the same eBPF bytecode to run across different kernel versions without needing to compile the eBPF program separately for each kernel version.
[0043] For example, for a directory content query operation, the eBPF program source code declares the kernel function names to be retrieved as dentry_open and iterate_dir. When loading the eBPF program, the loader searches for functions named dentry_open and iterate_dir in the kernel BTF information and obtains their function entry addresses and function prototype information. The obtained calling convention information includes: the dentry_open function has a first input parameter of type const char *, a second input parameter of type int, a third input parameter of type umode_t, and a return value of type struct file *; the iterate_dir function has a first input parameter of type struct file *, a second input parameter of type struct dir_context *, and a return value of type int.
[0044] The input parameter validation rules are generated based on the calling parameters and the calling conventions of the kernel's native functions. Taking the dentry_open function as an example, the path string / home / user / documents in the calling parameters needs to pass the following checks in sequence: Path string length validation confirms that the string length is between 1 and 4096 bytes; valid character set validation confirms that each character in the string belongs to a valid character set, which typically includes uppercase and lowercase letters, numbers, forward slashes, hyphens, underscores, periods, and spaces—characters allowed by the file system; pointer address validity validation confirms that the memory address pointing to the string is within the valid range of the kernel address space; path access permission validation confirms that the current execution context has access permissions to the path. These validation rules are implemented as a series of conditional judgment instructions in the eBPF program, and each failed validation results in a jump to the error handling branch.
[0045] First, the call parameters are validated item by item according to the input parameter validation rules. After successful validation, the path string is read from the eBPFMap and placed into a kernel-accessible memory area. Next, the input parameters required for the dentry_open function call are constructed, with the path string pointer, the open flag combination O_RDONLY and O_DIRECTORY, and the file permission mode value 0 as the three input parameters. Then, a kernel function call to the dentry_open function is initiated. The calling method can be implemented through the eBPF kfunc mechanism, which is a subset of kernel functions marked as callable by eBPF programs. It can also be implemented through other kernel-allowed eBPF function calling methods. After obtaining the file structure pointer returned by the dentry_open function, the input parameters required for the iterate_dir function call are constructed, with the file structure pointer and a dir_context structure pointer as the input parameters. Finally, the iterate_dir function call is initiated to complete the directory traversal. This series of kernel function calls arranged in a predetermined order constitutes a kernel function call sequence for direct execution in kernel mode. This kernel function call sequence is equivalent to the operation performed by the command `ls -la --time-style=full-iso / home / user / documents` in the traditional scheme, but the execution process does not involve the construction and parsing of shell command text.
[0046] In alternative implementations, such as Figure 3 As shown, S230 uses the eBPF program to securely bind the operation intent with the kernel native function, generating a kernel function call sequence for direct execution in kernel mode, including: S231: Decompose the operation intent into multiple atomic execution steps, each atomic execution step corresponding to an independent eBPF subroutine, and preload all eBPF subroutines into the eBPF program array.
[0047] S232: Store the multiple atomic execution steps in the kernel-mode queue storage structure in the execution order.
[0048] S233: The eBPF tail call jumps sequentially to the corresponding eBPF subroutine in the execution order, generating the kernel function call sequence consisting of the multiple atomic execution steps.
[0049] In this embodiment, the operation intent can be decomposed into multiple atomic execution steps, each corresponding to an independent eBPF subroutine. The rules for decomposing the operation intent into atomic execution steps can be predefined, and there are execution order dependencies between the atomic execution steps of one operation intent. Each eBPF subroutine is a compiled eBPF bytecode fragment, loaded into the kernel during loading and obtaining its corresponding file descriptor. The file descriptors of all eBPF subroutines are stored in an eBPF program array, specifically in a Map (BPF Map Type ProgramArray) within the eBPF program array. This Map is of type BPF_MAP_TYPE_PROG_ARRAY, a key-value pair structure where the key is an array index and the value is the file descriptor of the eBPF program. eBPF tail calls are implemented through the helper function bpf_tail_call. This function takes a pointer to a Map of type BPF_MAP_TYPE_PROG_ARRAY and an array index as parameters. After execution, the current eBPF program terminates immediately and jumps to the eBPF subroutine corresponding to the index to continue execution. The original program's stack frame is not retained during the jump, so tail call jumps do not consume additional stack space, and the original program does not resume execution after the jump.
[0050] For example, the corresponding eBPF subroutine performs path parameter length validation, valid character set validation, and pointer address validity validation. After successful validation, it reads the path string from the eBPF Map and converts it into a kernel-accessible pointer format, storing the converted pointer in the Per-CPU Map. The corresponding eBPF subroutine then reads the path pointer from the Per-CPU Map, calls the kernel native function `dentry_open` to perform a directory open operation, and stores the returned `file` structure pointer in the Per-CPU Map. If `dentry_open` returns an error, the execution flow terminates and an error message is returned. The corresponding eBPF subroutine then reads the `file` structure pointer from the Per-CPU Map, calls the kernel native function `iterate_dir` to traverse directory entries, recording information such as file name, file type, and inode number for each entry. After traversal, the collected data is formatted into structured data and written to the Per-CPU Map.
[0051] The per-CPU queue uses a first-in, first-out (FIFO) queue structure to store data. The per-CPU queue map refers to a kernel-mode queue storage structure where each CPU core has its own independent copy. Each CPU core only accesses its own queue copy, preventing race conditions in multi-core concurrent scenarios and achieving safe concurrent access without the need for locking. In this embodiment, the atomic execution steps are pushed sequentially into the per-CPU queue map according to their execution order. For example, a value of 1 for the first item represents the first atomic execution step, a value of 2 for the second item represents the second atomic execution step, and a value of 3 for the third item represents the third atomic execution step.
[0052] The kernel calls are executed sequentially via eBPF tail calls, jumping to the corresponding eBPF subroutines in order of execution. The main control program pops an atomic step number from the per-CPU queue map, searches for the corresponding eBPF subroutine file descriptor in the eBPF program array map based on the number, and then calls the `bpf_tail_call` helper function to jump to that subroutine for execution. After the subroutine completes execution, it jumps back to the main control program via a tail call. The main control program then pops the next atomic step number from the per-CPU queue map, repeating the above process until the queue is empty and all atomic execution steps have been completed. These sequentially executed atomic execution steps together constitute the kernel function call sequence.
[0053] The execution result of the previous subroutine can be passed to the next subroutine via the Per-CPU Map. For example, the pointer to the file structure obtained after the second atomic execution step opens the directory is stored under a predefined key in the Per-CPU Map. The third atomic execution step reads the pointer to the file structure under the same key from the Per-CPU Map, thus achieving context passing of the execution result. If any atomic step fails during execution, the main control program can decide to terminate the entire execution flow or execute predefined exception handling steps.
[0054] For example, the intent of the composite operation is to find and terminate a process with a specific name whose CPU utilization exceeds a preset threshold. This composite operation intent can be decomposed into the following atomic execution steps: The first atomic execution step is process list retrieval, where the corresponding eBPF subroutine obtains information such as process ID, process name, and CPU utilization of all processes in the system by traversing the kernel process control block linked list or calling kernel functions; the second atomic execution step is process filtering, where the corresponding eBPF subroutine filters the process list obtained in the previous step to select a list of process IDs whose process names match and whose CPU utilization exceeds the preset threshold; the third atomic execution step is process termination, where the corresponding eBPF subroutine sends a termination signal to each process in turn according to the selected process ID list. The sequence numbers of the above atomic execution steps are stored in the Per-CPU queue Map in execution order, and are scheduled for execution sequentially by the main control program through eBPF tail calls. Data between steps is transferred through the Per-CPU Map.
[0055] In alternative implementations, such as Figure 4 As shown, the multi-layer security verification performed by S300 during the generation of the kernel function call sequence includes: S310: During the MCP protocol payload parsing process, the format verification, length verification, and whitelist verification of the calling parameters are completed synchronously. If the verification fails, the processing is terminated. S320: During the process of binding the operation intention with the kernel native function, the operation permission verification, operation scope verification and risk level verification are completed simultaneously. If the verification fails, the processing is terminated. S330: Before executing the kernel function call sequence, a mandatory access control verification is performed through the eBPF LSM hook. After the verification is passed, the kernel function call sequence is executed in the kernel-mode eBPF security sandbox.
[0056] In this embodiment, multi-layered security checks are distributed across three different stages of request processing. The first layer of checks is performed synchronously during the MCP protocol payload parsing process, performing format checks, length checks, and whitelist checks on the call parameters. Format checks confirm that the data type of each parameter in the call parameters matches the parameter type defined in the tool descriptor. For example, path parameters should be strings and not arrays or objects, and numeric parameters should be valid values and not strings. Length checks confirm that the length of string parameters in the call parameters is within the maximum length limit defined in the tool descriptor, and the number of elements in array parameters is within the maximum number limit. Whitelist checks confirm that the values of enumeration parameters in the call parameters are within a predefined whitelist of valid values. For example, operation type parameters are only allowed to be read or list. If any of the above checks fails, the processing flow is immediately terminated and an error response indicating parameter validation failure is returned, specifying the name of the failed parameter and the reason for the failure. This layer of checks filters out parameters with incorrect formats at an early stage of the request processing flow, preventing illegal parameters from entering subsequent steps.
[0057] The second layer of verification is performed synchronously during the binding process between the operation intent and the kernel native function, verifying operation permissions, operation scope, and risk level. Operation permission verification confirms that the current execution context has the necessary permissions to execute the operating system operation corresponding to the operation intent. The execution context's permission information can be determined from the user ID and group ID obtained by the `bpf_get_current_uid_gid` helper function of the eBPF program, or from permission credentials obtained from other context sources. For example, a directory query operation requires verification that the execution context has read permissions to the target directory. This can be done by checking if the execution context's user ID matches the target directory's file owner ID, or by checking if other users' readable flags are set in the target directory's file permission bits. A process termination operation requires verification that the execution context has process management permissions. This can be done by checking if the execution context has the `CAP_SYS_ADMIN` or `CAP_KILL` permissions. Operation scope verification confirms that the target scope of the operation is within the allowed access range. The allowed access range can be a predefined file system path whitelist, such as only allowing access to files in the ` / data` directory and its subdirectories, or a predefined list of process names, such as only allowing the termination of processes belonging to a specific application group. Risk level verification assesses whether the risk level of the current operation conforms to the security policy of the current execution context. Different operation intentions can be pre-assigned different risk level values; for example, file reading is a low-risk level, and process termination is a high-risk level. The security policy of a specific execution context specifies the upper limit of the allowed risk level. If any of the above verifications fails, the processing flow is terminated and an error response indicating permission verification failure is returned.
[0058] The third layer of verification performs mandatory access control checks before the execution of the kernel function call sequence, using eBPF LSM hooks. eBPF LSM refers to Linux security module hooks implemented based on eBPF, used for kernel-mode mandatory access control. The Linux Security Module Framework (SMB) is a security mechanism provided by the kernel, allowing developers to insert security checkpoints into critical operation paths of the kernel using security modules; these checkpoints are called LSM hooks. eBPF LSM hooks are a feature introduced in Linux kernel version 5.7, allowing eBPF programs to be mounted as security modules to LSM hook points, executing custom security verification logic before the kernel performs sensitive operations. Predefined mandatory access control rules are written as eBPF programs and mounted to the corresponding LSM hook points; for example, mounting to the `file_open` hook to verify file open operations, and mounting to the `task_kill` hook to verify process termination operations. When a kernel native function call is executed in the kernel function call sequence, if the call triggers an LSM hook, the mounted eBPF program is called and executed. The program checks whether the subject identifier, object identifier, and operation type of the operation conform to the access control rules. If the check passes, the kernel function call is allowed to be executed. If the check fails, the kernel operation is intercepted and a permission denied error is returned.
[0059] After successful verification, the kernel function call sequence is executed in the kernel-mode eBPF security sandbox. The eBPF security sandbox consists of static security constraints from the eBPF verifier, kernel memory protection mechanisms, and eBPF runtime constraints. Before loading the program, the eBPF verifier performs static analysis to verify that the program does not contain risks such as memory out-of-bounds access, null pointer dereferences, infinite loops, or illegal kernel function calls. The kernel memory protection mechanism ensures that the eBPF program can only access its authorized memory regions. eBPF runtime constraints limit the maximum number of instructions that can be executed and the range of callable helper functions. When the kernel function call sequence is executed in the kernel-mode eBPF security sandbox, the entire execution process is constrained by the above security mechanisms; even if the orchestration logic of the kernel function call sequence is flawed, it will not lead to kernel memory corruption or kernel crashes.
[0060] In alternative implementations, such as Figure 5 As shown, the method further includes steps prior to executing the kernel function call sequence: S400: Binds the TCP connection information of the MCP client with the generated session identifier to obtain the session identifier information.
[0061] S500: Obtain session information based on the identifier of a single tool call request, the operation intent, the execution status, and the context data.
[0062] S600: Store the session identifier information and the session information into a kernel-mode key-value storage structure.
[0063] In this embodiment, after receiving the tool call request from the MCP client and before executing the kernel function call sequence, stateful session management can be performed through the Per-CPU eBPF Map. The Per-CPU eBPF Map refers to a kernel-mode key-value storage structure where each CPU core has an independent storage copy. The characteristic of this storage structure is that it creates an independent data copy for each CPU core. When a CPU core accesses data, it only operates on its own corresponding copy. There is no cache line contention between different cores. Therefore, in multi-core concurrent scenarios, there is no need to use synchronization mechanisms such as spinlocks or mutexes to achieve concurrent and safe data access. Per-CPU eBPF Maps include types such as Per-CPU Hash Map, Per-CPU Array Map, and Per-CPU Queue Map. These types have similar interfaces and usage methods to their corresponding non-Per-CPU versions, the difference being that each CPU core has an independent data copy.
[0064] The TCP connection information of the MCP client is bound to the generated session identifier and stored in a Per-CPU hash map. The TCP connection information includes the client IP address, client port number, server IP address, and server port number; these are collectively referred to as the TCP connection's four-tuple or five-tuple information. After the MCP client and server successfully establish a TCP connection, the server generates a session identifier for that TCP connection. The session identifier can be an incrementing integer value, a randomly generated UUID, or other unique identifier. The concatenated value of the source IP address, source port, destination IP address, destination port, and transport layer protocol from the TCP connection information is used as the key, and the session identifier as the value, stored in the Per-CPU hash map. Alternatively, the session identifier can be used as the key, and TCP connection information and session state information such as session creation time and last active time can be used as the value, stored in another Per-CPU hash map to achieve bidirectional indexing. Subsequently, when the server receives a TCP packet, it can extract the TCP connection information from the packet header, look up the corresponding session identifier in the Per-CPU hash map, and confirm the session to which the request belongs.
[0065] The identifier, operation intent, execution status, and context data of a single tool call request are stored in a Per-CPU array (Map). The identifier of a single tool call request is the `id` field value parsed from the MCP protocol request message. This value is generated by the client and is unique within the client's request scope. The Per-CPU array (Map) uses array indices as indexes to map the request identifier value to an array index, storing the request's processing information in the corresponding array element. The stored request processing information includes the request identifier, the mapped operation intent identifier, the processing progress status enumeration value, and the context data generated during execution. The processing progress status can include status values such as received and pending processing, intent mapping completed, security verification in progress, executing, execution completed, and execution failed. By storing the request processing information in the Per-CPU array (Map), the server can quickly locate the corresponding request's processing information at any processing stage using the request identifier, achieving stateful request processing management.
[0066] For example, when the server handles multiple concurrent tool call requests from multiple clients, each request can be allocated to a CPU core that processes the request data. During the processing of a request, the server writes the request identifier and the current processing state into a Per-CPU array (Map). When the processing of the request needs to switch between different stages, the previously stored state information and context data can be read from the Per-CPU array (Map) to continue processing, thus achieving state persistence across processing stages.
[0067] In alternative implementations, such as Figure 6 As shown, step S200, which maps tool names to predefined operational intents, includes: S240: Using a predefined mapping table, the tool name is associated with the corresponding operation intent. The mapping table stores the correspondence between the tool name and the operation intent, as well as the parameter constraint rules corresponding to each operation intent.
[0068] S250: After matching the corresponding operation intent, the format of the call parameters is validated according to the parameter constraint rules.
[0069] In this embodiment, tool names are mapped to predefined operation intentions, and the association and matching are performed through a predefined mapping table. The mapping table is a key-value pair data set, where the key is the tool name string and the value is a structure containing the operation intention identifier and parameter constraint rules. The mapping table is loaded and constructed from the tool descriptor configuration file during the server-side initialization phase. The tool descriptor is a configuration file containing the tool name, function description, parameter constraints, and security policies, and each tool corresponds to one tool descriptor.
[0070] The mapping table is constructed as follows: When the server starts, it scans a predefined tool configuration directory. This directory can be a specified path in the server's local file system, containing JSON or YAML tool descriptor files for all registered tools. The server iterates through each file in the tool configuration directory, reading its contents and parsing them into a tool descriptor structure. Each tool descriptor contains a tool name field, a function description field, an input parameter schema field, a security policy field, and an operation intent field. The tool name field stores the tool's unique identifier, such as `list_directory`. The input parameter schema field defines the constraints of the parameters accepted by the tool, including their name, type, whether they are required, default value, maximum length, and a list of valid values, described using the JSON Schema specification. The operation intent field stores the operation intent identifier associated with the tool, such as a directory content query. The server stores the tool name as the key, the operation intent identifier, and the input parameter schema as the value in the mapping table for each tool descriptor.
[0071] After matching the corresponding operation intent, the call parameters are validated according to parameter constraint rules. The server retrieves the input parameter schema associated with the operation intent from the mapping table and checks each field in the call parameters to ensure it conforms to the type, length, and value constraints defined in the schema. If the call parameters contain fields not defined in the schema, the server decides whether to reject the request or ignore the extra fields based on the security policy. If a field marked as required in the schema is missing from the call parameters, validation fails and an error response indicating a missing required parameter is returned. If the type of a field in the call parameters does not match the type defined in the schema (e.g., passing a numeric type as a string parameter), validation fails and a parameter type error response is returned.
[0072] For example, the tool descriptor corresponding to the `list_directory` tool defines the following input parameter `schema`: parameter name is `path`, parameter type is `string`, parameter is required, maximum length is 4096 bytes, and the valid character set includes uppercase and lowercase letters, numbers, forward slashes, underscores, hyphens, and periods. When a client calls the `list_directory` tool and passes in the path parameter, the server verifies whether the `path` parameter is of type string, whether its length is within 4096 bytes, and whether each character is within the valid character set. After all verifications pass, the operation intent indicating directory content query and the verified path parameter are passed to subsequent steps, entering the kernel-mode function call sequence generation and execution flow.
[0073] In alternative implementations, such as Figure 7As shown, the process of S300 encapsulating the execution result according to the MCP protocol specification and returning it to the MCP client includes: S340: Convert the execution result into structured data that conforms to the MCP specification.
[0074] S350: Fill the structured data into the response message, which includes a protocol version field, a request identifier field, and an execution result field.
[0075] S360: Sends the encapsulated response message to the MCP client via a TCP connection.
[0076] In this embodiment, after executing the kernel function call sequence and obtaining the execution result, the execution result is encapsulated and returned. The result obtained from executing the kernel function call sequence may include the following forms: a data structure pointer returned from a native kernel function, an integer error code returned from a native kernel function, and structured data passed through an eBPF Map. For directory content query operations, the execution result is a list of file information collected after traversing directory entries using the iterate_dir function. Each file information entry includes fields such as file name, inode number, file type, file size, file owner user ID, file owner group ID, permission bits, last access time, and last modification time. For file content reading operations, the execution result is the byte sequence of the read file content and the actual number of bytes read. For process list query operations, the execution result is a list of process information, each process information entry including fields such as process ID, parent process ID, process name, process status, CPU usage time, and memory usage.
[0077] The execution results are converted into structured data conforming to the MCP specification. This conversion process maps kernel-mode data structures to a data format that can be accommodated by JSON RPC 2.0 response messages. Taking directory content query as an example, each file entry in the file information list is converted into a JSON object. Each field is named according to the field names agreed upon in the MCP specification; for example, the file name is named `name`, the file size is named `size_bytes`, the file type is named `type`, and the last modified time is named `modified_at`. All JSON objects are then organized into a JSON array as the value of the `result` field. This conversion process can be completed in the kernel-mode eBPF program, or the original data can be passed to user-mode via an eBPF Map, and then the user-mode program performs JSON serialization.
[0078] Structured data is populated into the JSON RPC 2.0 response message. The response message includes a jsonrpc field, an id field, and a result field or an error field. The jsonrpc field value is always a string 2.0. The id field value is exactly the same as the id field value in the corresponding request message to ensure the client can associate the response with the previously sent request. If execution is successful, the result field contains structured execution result data, whose value can be a JSON object, a JSON array, a string, a number, a boolean value, or null. If execution fails, the result field is omitted, but an error field is included instead. The error field is a JSON object, where the code subfield is a numeric error code, the message subfield is a string error description, and the data subfield is optional and can contain additional error details. After encapsulation, the response message is written to the send buffer and sent to the MCP client via a TCP connection, completing the entire process of a tool invocation request.
[0079] In alternative implementations, such as Figure 8 As shown, S100 receives a tool invocation request sent by the MCP client, and parses it to obtain the tool name and invocation parameters, including: S110: The eBPF program, mounted to the kernel network hook point, receives network packets from the MCP client in kernel mode.
[0080] S120: In kernel mode, perform TCP stream reassembly on the network packets to extract the MCP protocol payload.
[0081] S130: Perform zero-copy parsing on the MCP protocol payload to obtain the tool name and calling parameters.
[0082] In this embodiment, the process of receiving a tool invocation request sent by the MCP client and parsing it to obtain the tool name and invocation parameters can be implemented through a kernel-mode eBPF program. Compared to the user-mode receiving method, the kernel-mode eBPF program implementation avoids the memory copying overhead of network packets from kernel space to user space, and also avoids the system call overhead of context switching between user mode and kernel mode.
[0083] The eBPF program, mounted to a kernel network hook point, receives network packets from the MCP client in kernel mode. A kernel network hook point is an execution node provided at different layers of the Linux kernel network protocol stack, where an eBPF program can be mounted. When a packet passes through the corresponding node, the mounted eBPF program is invoked and executed. The kernel network hook points used in this embodiment may include the XDP ingress hook, the TC ingress hook, and the BPF_SOCK_OPS hook.
[0084] XDP (Express Data Path) is a kernel network hook interface located in the network interface card (NIC) driver layer. The XDP ingress hook is positioned between the NIC driver receiving a network packet and before passing it to the kernel network protocol stack; it is the first execution point where an eBPF program can be attached after the packet enters the kernel processing flow. The eBPF program attached to the XDP ingress hook can obtain the complete Ethernet frame, IP header, and TCP header information of the packet and perform filtering and judgment. If the TCP destination port number of the packet is not the listening port number of the MCP server, the eBPF program directly returns the XDP_DROP action, discarding the packet at the NIC driver layer and preventing it from entering the subsequent kernel protocol stack processing flow. If the destination port number of the packet is the server's listening port, it returns the XDP_PASS action, allowing the packet to pass to the kernel network protocol stack for further processing. Filtering illegal packets at the XDP ingress hook point prevents invalid packets from consuming kernel protocol stack processing resources.
[0085] TC (Traffic Control) is a hook interface located at the network layer of the kernel network protocol stack. The TC ingress hook sits after IP layer processing and before TCP layer processing. eBPF programs attached to the TC ingress hook can obtain complete IP and TCP packet contents and further process legitimate packets filtered by the XDP ingress hook. The eBPF program on the TC ingress hook performs integrity checks and extracts session information from the packets, associating them with the corresponding TCP connections to provide the data foundation for subsequent TCP stream reassembly.
[0086] BPF_SOCK_OPS refers to a kernel-provided hook interface used to intercept TCP socket state changes. eBPF programs attached to the BPF_SOCK_OPS hook can intercept TCP socket connection establishment, connection closure, state changes, timeout retransmissions, and other events. Through the BPF_SOCK_OPS hook, the entire lifecycle management of an MCP client TCP connection can be completed in kernel space: recording the connection's five-tuple information and initial sequence number upon completion of the TCP three-way handshake, marking the connection as established; updating the connection state to closed upon completion of the TCP four-way handshake, and cleaning up kernel-space session data associated with the connection; and logging exceptions as needed when TCP timeout retransmission events occur.
[0087] The MCP protocol is based on TCP transmission, and the MCP payload is a complete JSON RPC 2.0 message text from the application layer. Since TCP is a byte-stream oriented transport protocol, network packets may be fragmented and out of order during transmission. An MCP payload may be split into multiple TCP packets for transmission. The TCP stream reassembly process involves tracking the data flow in the receiving direction of the TCP connection in kernel space. Out-of-order TCP packets are reassembled according to their sequence numbers. Fragmented packets are identified, and TCP segments belonging to the same application layer packet are merged. The TCP and IP headers are removed, and the continuous and complete application layer payload data, i.e., the MCP payload, is extracted. During stream reassembly, the checksum, sequence number, and acknowledgment number of the TCP packets are checked synchronously, and packets with checksum errors, duplicate sequence numbers, or those exceeding the window range are discarded.
[0088] Zero-copy parsing is performed on the MCP protocol payload to obtain the tool name and calling parameters. Zero-copy means that the parsing process does not perform memory block copying operations on the payload data. Instead, it directly parses fields and extracts content based on the original memory address where the network packet data is stored in the kernel socket buffer. The kernel socket buffer is a memory area in the kernel used to store network packet data. After the network card receives a packet and it is processed by the kernel protocol stack, the application layer payload data of the packet is stored in this buffer. Zero-copy parsing directly locates and reads the contents of each JSON field in the payload using memory address offsets, avoiding the overhead of memcpy operations that copy payload data from the socket buffer to another memory area, and also avoiding the overhead of copy_from_user or copy_to_user operations between user space and kernel space.
[0089] In alternative implementations, such as Figure 9 As shown, S130 performs zero-copy parsing of the MCP protocol payload to obtain the tool name and calling parameters, including: S131: Based on the raw message pointer of the kernel socket buffer, the core fields of the MCP protocol payload are located through a pre-compiled fixed-offset finite state machine.
[0090] S132: Perform synchronous validation on the format and length of the core field. If the validation fails, terminate the parsing and generate an error response.
[0091] S133: Extract the tool name and calling parameters from the core fields that have passed the verification.
[0092] In this embodiment, the specific implementation of zero-copy parsing of the MCP protocol payload is as follows: Based on the raw message pointer of the kernel socket buffer, the core fields of the MCP protocol payload are located through a pre-compiled fixed-offset finite state machine. The raw message pointer is a pointer to the starting byte of the application layer payload data in the kernel socket buffer, through which each byte of the payload data can be directly accessed. The pre-compiled fixed-offset finite state machine refers to a linear jump execution model that only contains the parsing logic of the fixed specification fields of the MCP protocol. This finite state machine is fixed as a series of conditional jump instructions during the compilation of the eBPF program. During the parsing process, the general JSON parsing algorithm is not executed; only the jsonrpc field, id field, method field, and params field fixedly contained in the tool call request in the MCP protocol are matched and extracted. Since the eBPF verifier requires that all loops must have a finite upper bound that can be determined at compile time, each loop of the finite state machine is set with a fixed upper bound. The upper bound value is set to the maximum message length allowed by the MCP protocol or the maximum length of each field, ensuring that the parsing logic can pass the static security verification of the eBPF verifier.
[0093] For example, a pre-compiled fixed-offset finite state machine may contain the following states and transition logic. In the initial state, the finite state machine maintains a byte pointer pointing to the current position of the payload data being read, and sequentially scans characters starting from the beginning of the payload data. The finite state machine first scans whitespace and newline characters, skipping leading whitespace in the JSON message, and then matches the first double quote character. If the match is successful, it enters the jsonrpc field parsing state. In the jsonrpc field parsing state, the finite state machine matches the string "jsonrpc", then the colon separator, and then the string "2.0", completing the reading and validation of the key and value content of the jsonrpc field. After validating that the value of the jsonrpc field is equal to "2.0", it matches the comma separator and jumps to the id field parsing state. In the id field parsing state, the finite state machine matches the string "id", the colon separator, and then reads an integer or string as the value content of the id field. After validating that the id field exists and recording its value, it matches the comma separator and jumps to the method field parsing state. In the `method` field parsing state, the finite state machine matches the string `method` and the colon separator, then reads the string `tools / call` as the value of the `method` field. After verifying that the value of the `method` field is `tools / call`, it matches the comma separator and jumps to the `params` field parsing state. In the `params` field parsing state, the finite state machine matches the string `params` and the colon separator, then reads a nested JSON object as the value of the `params` field, extracting the tool name and calling parameters from this nested JSON object. After completing the `params` field parsing, it matches the curly brace terminator and jumps to the ending state.
[0094] The format and length of core fields are validated synchronously. If validation fails, parsing terminates and an error response is generated. Format validation is performed synchronously when parsing each core field. Validation includes confirming that the value string of the jsonrpc field is 2.0, that the value string of the id field is a valid number or string and not null, that the value string of the method field is a valid method name defined by the MCP protocol, and that the value string of the params field is a valid JSON object and not null. Length validation confirms that the length of the value string of each core field or the length of the serialized object is within a predefined maximum length range. For example, the length of the jsonrpc field value string must not exceed 10 bytes, and the length of the method field value string must not exceed 128 bytes. If any field fails format or length validation, the finite state machine stops parsing and generates an error response containing an error code, error type, and error description.
[0095] The tool name and invocation parameters are extracted from the core fields that pass validation. For requests with the `method` field value of `tools / call`, the tool name and invocation parameters are extracted from the nested JSON object of the `params` field. The tool name is extracted from the agreed-upon tool name key in the nested `params` object, and the invocation parameters are extracted from the agreed-upon parameter key in the nested `params` object. The extracted tool name and invocation parameters are stored in the kernel-mode eBPF Map, providing input data for subsequent operation intent mapping and kernel function call sequence generation.
[0096] This application embodiment also provides an operating system configured to receive tool invocation requests sent by an MCP client, parse the tool name and invocation parameters, map the tool name to a predefined operation intent, and, based on the operation intent and invocation parameters, generate a kernel function call sequence for direct execution in kernel mode through an eBPF program mounted to the kernel, based on the attribute information of the target operating system corresponding to the tool invocation request; perform multi-layer security checks during the generation of the kernel function call sequence, execute the kernel function call sequence after the checks pass, and encapsulate the execution result according to the MCP protocol specification and return it to the MCP client.
[0097] Those skilled in the art will understand that the method and system provided in the embodiments of this application, by mapping tool names to operation intentions and then generating a kernel function call sequence for direct execution in kernel mode based on the operation intentions and call parameters through an eBPF program mounted to the kernel, replaces the traditional process of constructing shell command text and creating a child process to execute shell commands. The generation process of the kernel function call sequence retrieves the address and calling specification of the kernel native function corresponding to the operation intention through kernel BTF information retrieval, and directly binds the call parameters as input parameters of the kernel native function according to the function signature requirements. There is no shell parsing stage in the entire execution chain, and the call parameters are not subjected to lexical analysis and command parsing by any shell interpreter. Therefore, even if the parameters contain shell metacharacters, they do not constitute a condition for command injection. Request reception and parsing can be completed in kernel mode through an eBPF program mounted to the kernel network hook point, and result encapsulation and return are also completed in kernel mode, eliminating the overhead of data copying and context switching between user mode and kernel mode. Multi-layer security verification is distributed in the parsing stage, binding stage, and pre-execution stage. Each layer of verification is executed sequentially. If the previous layer of verification fails, the processing is terminated and does not proceed to the subsequent process. Through the combined effect of the above-mentioned technical features, while achieving low end-to-end processing latency, the security risks introduced by the construction and parsing of Shell command text are avoided at the execution mechanism level.
[0098] 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 cross-platform tool invocation method based on the MCP protocol, characterized in that, include: Receive tool invocation requests sent by the MCP client and parse them to obtain the tool name and invocation parameters; The tool name is mapped to a predefined operation intent. Based on the operation intent and the call parameters, and according to the attribute information of the target operating system corresponding to the tool call request, a kernel function call sequence for direct execution in kernel mode is generated by the eBPF program mounted to the kernel. During the generation of the kernel function call sequence, multi-layer security checks are performed. After the checks pass, the kernel function call sequence is executed, and the execution result is encapsulated according to the MCP protocol specification and returned to the MCP client.
2. The method according to claim 1, characterized in that, The generation of kernel function call sequences for direct execution in kernel mode by the eBPF program mounted to the kernel includes: After mapping the tool name to a predefined operation intent, the memory address and calling convention of the kernel native function corresponding to the operation intent are retrieved through kernel BTF information; Based on the calling parameters and the calling conventions of the kernel native functions, input parameter verification rules are generated; The eBPF program securely binds the operational intent to the kernel native function, generating a kernel function call sequence for direct execution in kernel mode.
3. The method according to claim 2, characterized in that, The step of securely binding the operation intent with the kernel native function through the eBPF program to generate a kernel function call sequence for direct execution in kernel mode includes: The operation intent is decomposed into multiple atomic execution steps, each atomic execution step corresponds to an independent eBPF subroutine, and all eBPF subroutines are preloaded into the eBPF program array; The multiple atomic execution steps are stored in the kernel-state queue storage structure in the order of execution. The eBPF tail call jumps sequentially to the corresponding eBPF subroutine in the execution order, generating the kernel function call sequence consisting of the multiple atomic execution steps.
4. The method according to claim 1, characterized in that, The multi-layer security verification performed during the generation of the kernel function call sequence includes: During the MCP protocol payload parsing process, the format verification, length verification, and whitelist verification of the calling parameters are performed synchronously. If the verification fails, the processing is terminated. During the process of binding the operation intent with the kernel native function, operation permission verification, operation scope verification, and risk level verification are performed simultaneously. If the verification fails, the process is terminated. Before executing the kernel function call sequence, a mandatory access control check is performed via an eBPF LSM hook so that the kernel function call sequence can be executed in the kernel-mode eBPF security sandbox after the check passes.
5. The method according to claim 1, characterized in that, Before executing the kernel function call sequence, the following is also included: Bind the TCP connection information of the MCP client with the generated session identifier to obtain the session identifier information; Session information is obtained based on the identifier of a single tool call request, the operation intent, the execution status, and the context data; The session identifier information and the session information are stored in a kernel-mode key-value storage structure.
6. The method according to claim 1, characterized in that, The mapping of tool names to predefined operational intents includes: The tool name is associated with the corresponding operation intention through a predefined mapping table. The mapping table stores the correspondence between tool name and operation intention, as well as the parameter constraint rules for each operation intention. After matching the corresponding operation intent, the format of the call parameters is validated according to the parameter constraint rules.
7. The method according to claim 1, characterized in that, The step of encapsulating the execution result according to the MCP protocol specification and returning it to the MCP client includes: The execution results are converted into structured data that conforms to the MCP specification; The structured data is populated into the response message, which includes a protocol version field, a request identifier field, and an execution result field. The encapsulated response message is sent to the MCP client via a TCP connection.
8. The method according to claim 1, characterized in that, The tool invocation request sent by the MCP client is parsed to obtain the tool name and invocation parameters, including: The eBPF program, mounted to the kernel network hook point, receives network packets from the MCP client in kernel mode. In kernel mode, TCP stream reassembly is performed on the network packets to extract the MCP protocol payload; The tool name and calling parameters are obtained by zero-copy parsing of the MCP protocol payload.
9. The method according to claim 8, characterized in that, The zero-copy parsing of the MCP protocol payload to obtain the tool name and calling parameters includes: Based on the raw message pointer of the kernel socket buffer, the core fields of the MCP protocol payload are located through a pre-compiled fixed-offset finite state machine; The format and length of the core fields are validated synchronously. If the validation fails, the parsing is terminated and an error response is generated. Extract the tool name and calling parameters from the core fields that have passed the verification.
10. An operating system, characterized in that, Configured to receive tool invocation requests sent by MCP clients, parse the tool name and invocation parameters; map the tool name to a predefined operation intent; and generate a kernel function call sequence for direct execution in kernel mode by an eBPF program mounted to the kernel based on the operation intent and invocation parameters and the attribute information of the target operating system corresponding to the tool invocation request. During the generation of the kernel function call sequence, multi-layer security checks are performed. After the checks pass, the kernel function call sequence is executed, and the execution result is encapsulated according to the MCP protocol specification and returned to the MCP client.