Python LSP JSON-RPC

1.1.2 · active · verified Sat Apr 11

python-lsp-jsonrpc is a Python 3.8+ server implementation of the JSON RPC 2.0 protocol. This library was extracted from the Python LSP Server project to provide a standalone JSON-RPC core. It is currently at version 1.1.2 and receives updates as needed for bug fixes and minor feature enhancements.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates a basic JSON-RPC server handling two methods: `sum` and `notify_exit`. The server communicates over standard I/O, expecting JSON-RPC requests on stdin and sending responses to stdout. To run, save as `server.py` and execute `python server.py`. You can then send JSON-RPC requests via a client (e.g., using `echo '{"jsonrpc": "2.0", "method": "sum", "params": {"a": 1, "b": 2}, "id": 1}' | python server.py`).

import logging
import sys

from jsonrpc.manager import JSONRPCMethodManager
from jsonrpc.server import JSONRPCServer

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
handler = logging.StreamHandler(sys.stderr)
handler.setFormatter(logging.Formatter('%(levelname)s: %(message)s'))
logger.addHandler(handler)


class ExampleManager(JSONRPCMethodManager):
    def sum(self, a, b):
        logger.info(f"Received sum request for {a}, {b}")
        return a + b

    def notify_exit(self):
        logger.info("Received exit notification.")
        sys.exit(0)


def main():
    manager = ExampleManager()
    server = JSONRPCServer(manager)
    logger.info("Starting JSON RPC server (STDIO). Send JSON RPC requests via stdin.")
    server.serve_forever()


if __name__ == '__main__':
    main()

view raw JSON →