python-1c-mcp 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3 @@
1
+ """Read-only MCP server for 1C:Enterprise standard OData."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,130 @@
1
+ """Environment-based Infobase connection (one shared session per process)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import os
7
+ from dataclasses import dataclass
8
+ from urllib.parse import unquote, urlparse
9
+
10
+ from python_1c_odata import Infobase
11
+
12
+ _FORMATS = frozenset({"json", "atom", "auto"})
13
+ _TRUTHY = frozenset({"1", "true", "yes", "on"})
14
+
15
+
16
+ class ConfigError(ValueError):
17
+ """Missing or invalid connection settings."""
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class ConnectionConfig:
22
+ server: str
23
+ infobase: str
24
+ username: str
25
+ password: str
26
+ format: str = "json"
27
+ debug: bool = False
28
+
29
+
30
+ _lock = asyncio.Lock()
31
+ _infobase: Infobase | None = None
32
+ _config: ConnectionConfig | None = None
33
+
34
+
35
+ def parse_onec_url(url: str) -> ConnectionConfig:
36
+ """Parse ``http://user:pass@host:port/publication`` into connection fields."""
37
+ parsed = urlparse(url.strip())
38
+ if parsed.scheme not in {"http", "https"}:
39
+ raise ConfigError(f"ONEC_URL scheme must be http or https, got {parsed.scheme!r}")
40
+ if not parsed.hostname:
41
+ raise ConfigError("ONEC_URL must include a host")
42
+ if not parsed.username or parsed.password is None:
43
+ raise ConfigError("ONEC_URL must include user:pass@ in the authority")
44
+ path = parsed.path.strip("/")
45
+ if not path:
46
+ raise ConfigError("ONEC_URL must include the infobase publication path")
47
+ port = f":{parsed.port}" if parsed.port else ""
48
+ server = f"{parsed.scheme}://{parsed.hostname}{port}"
49
+ return ConnectionConfig(
50
+ server=server,
51
+ infobase=path.split("/")[0],
52
+ username=unquote(parsed.username),
53
+ password=unquote(parsed.password),
54
+ format=os.environ.get("ONEC_FORMAT", "json"),
55
+ debug=os.environ.get("ONEC_DEBUG", "").lower() in _TRUTHY,
56
+ )
57
+
58
+
59
+ def load_config() -> ConnectionConfig:
60
+ """Load connection settings from environment variables."""
61
+ url = os.environ.get("ONEC_URL")
62
+ if url:
63
+ cfg = parse_onec_url(url)
64
+ else:
65
+ missing = [
66
+ name
67
+ for name, value in (
68
+ ("ONEC_SERVER", os.environ.get("ONEC_SERVER")),
69
+ ("ONEC_INFOBASE", os.environ.get("ONEC_INFOBASE")),
70
+ ("ONEC_USER", os.environ.get("ONEC_USER")),
71
+ ("ONEC_PASSWORD", os.environ.get("ONEC_PASSWORD")),
72
+ )
73
+ if not value
74
+ ]
75
+ if missing:
76
+ raise ConfigError(
77
+ "Missing required environment variable(s): "
78
+ + ", ".join(missing)
79
+ + ". Set them individually or use ONEC_URL=http://user:pass@host/base"
80
+ )
81
+ fmt = os.environ.get("ONEC_FORMAT", "json")
82
+ cfg = ConnectionConfig(
83
+ server=os.environ["ONEC_SERVER"].strip(),
84
+ infobase=os.environ["ONEC_INFOBASE"].strip(),
85
+ username=os.environ["ONEC_USER"],
86
+ password=os.environ["ONEC_PASSWORD"],
87
+ format=fmt,
88
+ debug=os.environ.get("ONEC_DEBUG", "").lower() in _TRUTHY,
89
+ )
90
+ if cfg.format not in _FORMATS:
91
+ raise ConfigError(f"ONEC_FORMAT must be one of {sorted(_FORMATS)}, got {cfg.format!r}")
92
+ return cfg
93
+
94
+
95
+ def validate_config() -> ConnectionConfig:
96
+ """Validate env at startup; cache config for lazy Infobase init."""
97
+ global _config
98
+ _config = load_config()
99
+ return _config
100
+
101
+
102
+ def _build_infobase(cfg: ConnectionConfig) -> Infobase:
103
+ return Infobase(
104
+ cfg.server,
105
+ cfg.infobase,
106
+ cfg.username,
107
+ cfg.password,
108
+ format=cfg.format,
109
+ debug=cfg.debug,
110
+ )
111
+
112
+
113
+ async def get_infobase() -> Infobase:
114
+ """Return the shared Infobase, creating the HTTP session on first use."""
115
+ global _infobase
116
+ async with _lock:
117
+ if _infobase is None:
118
+ cfg = _config if _config is not None else load_config()
119
+ _infobase = _build_infobase(cfg)
120
+ await _infobase._ensure_session()
121
+ return _infobase
122
+
123
+
124
+ async def close_infobase() -> None:
125
+ """Close the shared HTTP session."""
126
+ global _infobase
127
+ async with _lock:
128
+ if _infobase is not None:
129
+ await _infobase.aclose()
130
+ _infobase = None
@@ -0,0 +1,19 @@
1
+ """Generic entity-set access by full OData name (Catalog_*, Document_*, ...)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from python_1c_odata.client import Infobase
6
+ from python_1c_odata.entity import EntitySet
7
+
8
+
9
+ class NamedEntitySet(EntitySet):
10
+ """Query any published entity set using its full name (e.g. ``Catalog_Товары``)."""
11
+
12
+ kind = ""
13
+
14
+ def __init__(self, infobase: Infobase, full_name: str) -> None:
15
+ super().__init__(infobase, full_name)
16
+
17
+ @property
18
+ def entity(self) -> str:
19
+ return self.name
@@ -0,0 +1,150 @@
1
+ """Read-only MCP server for 1C:Enterprise standard OData."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import sys
7
+ from collections.abc import AsyncIterator
8
+ from contextlib import asynccontextmanager
9
+
10
+ from mcp.server.mcpserver import MCPServer
11
+
12
+ from python_1c_mcp.connection import ConfigError, close_infobase, validate_config
13
+ from python_1c_mcp.tools import handlers
14
+
15
+ _LOG = logging.getLogger("python_1c_mcp")
16
+
17
+ INSTRUCTIONS = """\
18
+ Read-only MCP server for 1C:Enterprise standard OData (platform 8.3.5+, standard.odata publication).
19
+
20
+ Available read operations only — no create, update, delete, or post/unpost.
21
+ Use list_entity_sets and describe_entity_set to discover schema, then odata_query or get_entity.
22
+ """
23
+
24
+
25
+ @asynccontextmanager
26
+ async def _lifespan(_server: MCPServer) -> AsyncIterator[None]:
27
+ try:
28
+ yield
29
+ finally:
30
+ await close_infobase()
31
+
32
+
33
+ mcp = MCPServer(
34
+ "python-1c-mcp",
35
+ title="1C OData (read-only)",
36
+ instructions=INSTRUCTIONS,
37
+ lifespan=_lifespan,
38
+ )
39
+
40
+
41
+ @mcp.tool(
42
+ name="list_entity_sets",
43
+ description=(
44
+ "List all OData entity set names published by the connected 1C infobase "
45
+ "(Catalog_*, Document_*, register names, etc.). Read-only."
46
+ ),
47
+ )
48
+ async def list_entity_sets() -> dict:
49
+ return await handlers.list_entity_sets()
50
+
51
+
52
+ @mcp.tool(
53
+ name="describe_entity_set",
54
+ description=(
55
+ "Describe keys, scalar properties, and navigation properties for one entity set. "
56
+ "Pass the full set name, e.g. Catalog_Товары. Read-only."
57
+ ),
58
+ )
59
+ async def describe_entity_set(entity_set: str) -> dict:
60
+ return await handlers.describe_entity_set(entity_set)
61
+
62
+
63
+ @mcp.tool(
64
+ name="odata_query",
65
+ description=(
66
+ "Run a read-only OData query against an entity set. Supports $filter, $select, "
67
+ "$top (default 20, max 100), $skip, $orderby, and $inlinecount. Read-only."
68
+ ),
69
+ )
70
+ async def odata_query(
71
+ entity_set: str,
72
+ odata_filter: str | None = None,
73
+ select: str | None = None,
74
+ top: int = 20,
75
+ skip: int | None = None,
76
+ orderby: str | None = None,
77
+ inlinecount: bool = False,
78
+ ) -> dict:
79
+ return await handlers.odata_query(
80
+ entity_set,
81
+ odata_filter=odata_filter,
82
+ select=select,
83
+ top=top,
84
+ skip=skip,
85
+ orderby=orderby,
86
+ inlinecount=inlinecount,
87
+ )
88
+
89
+
90
+ @mcp.tool(
91
+ name="get_entity",
92
+ description=(
93
+ "Fetch a single entity record by Ref_Key GUID from an entity set. Read-only."
94
+ ),
95
+ )
96
+ async def get_entity(
97
+ entity_set: str,
98
+ ref_key: str,
99
+ select: str | None = None,
100
+ ) -> dict:
101
+ return await handlers.get_entity(entity_set, ref_key, select=select)
102
+
103
+
104
+ @mcp.tool(
105
+ name="get_metadata",
106
+ description=(
107
+ "Return OData $metadata summary (entity set count and sample names). "
108
+ "Set raw_xml=true for truncated XML. Read-only."
109
+ ),
110
+ )
111
+ async def get_metadata(raw_xml: bool = False) -> dict:
112
+ return await handlers.get_metadata(raw_xml=raw_xml)
113
+
114
+
115
+ @mcp.resource(
116
+ "1c://entity-sets",
117
+ name="entity-sets",
118
+ description="Cached list of all OData entity set names from $metadata.",
119
+ mime_type="text/plain",
120
+ )
121
+ async def entity_sets_resource() -> str:
122
+ return await handlers.resource_entity_sets()
123
+
124
+
125
+ @mcp.resource(
126
+ "1c://metadata",
127
+ name="metadata",
128
+ description="Raw or truncated $metadata XML from the connected infobase.",
129
+ mime_type="application/xml",
130
+ )
131
+ async def metadata_resource() -> str:
132
+ return await handlers.resource_metadata()
133
+
134
+
135
+ def main() -> None:
136
+ logging.basicConfig(
137
+ level=logging.INFO,
138
+ format="%(levelname)s %(name)s: %(message)s",
139
+ stream=sys.stderr,
140
+ )
141
+ try:
142
+ validate_config()
143
+ except ConfigError as exc:
144
+ print(f"python-1c-mcp: {exc}", file=sys.stderr)
145
+ sys.exit(1)
146
+ mcp.run(transport="stdio")
147
+
148
+
149
+ if __name__ == "__main__":
150
+ main()
@@ -0,0 +1 @@
1
+ """Read-only tool handlers."""
@@ -0,0 +1,139 @@
1
+ """Read-only MCP tool implementations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from python_1c_odata.metadata import EntityTypeInfo
8
+
9
+ from python_1c_mcp.connection import get_infobase
10
+ from python_1c_mcp.entity_set import NamedEntitySet
11
+
12
+ _LIST_TRUNCATE_AT = 500
13
+ _METADATA_XML_LIMIT = 8000
14
+ _DEFAULT_TOP = 20
15
+ _MAX_TOP = 100
16
+
17
+
18
+ def entity_type_to_dict(info: EntityTypeInfo) -> dict[str, Any]:
19
+ return {
20
+ "name": info.name,
21
+ "keys": list(info.keys),
22
+ "properties": [
23
+ {"name": prop.name, "type": prop.type, "nullable": prop.nullable}
24
+ for prop in info.properties
25
+ ],
26
+ "navigation_properties": list(info.navigation_properties),
27
+ }
28
+
29
+
30
+ async def list_entity_sets() -> dict[str, Any]:
31
+ ib = await get_infobase()
32
+ names = await ib.entity_sets()
33
+ total = len(names)
34
+ truncated = total > _LIST_TRUNCATE_AT
35
+ if truncated:
36
+ names = names[:_LIST_TRUNCATE_AT]
37
+ result: dict[str, Any] = {
38
+ "total": total,
39
+ "entity_sets": names,
40
+ "truncated": truncated,
41
+ }
42
+ if truncated:
43
+ result["message"] = (
44
+ f"Listing truncated to first {_LIST_TRUNCATE_AT} of {total} entity sets."
45
+ )
46
+ return result
47
+
48
+
49
+ async def describe_entity_set(entity_set: str) -> dict[str, Any]:
50
+ ib = await get_infobase()
51
+ info = await ib.entity_type_for_set(entity_set)
52
+ return entity_type_to_dict(info)
53
+
54
+
55
+ async def odata_query(
56
+ entity_set: str,
57
+ *,
58
+ odata_filter: str | None = None,
59
+ select: str | None = None,
60
+ top: int = _DEFAULT_TOP,
61
+ skip: int | None = None,
62
+ orderby: str | None = None,
63
+ inlinecount: bool = False,
64
+ ) -> dict[str, Any]:
65
+ if top < 1:
66
+ raise ValueError("top must be at least 1")
67
+ if top > _MAX_TOP:
68
+ raise ValueError(f"top cannot exceed {_MAX_TOP}")
69
+ if skip is not None and skip < 0:
70
+ raise ValueError("skip must be non-negative")
71
+
72
+ ib = await get_infobase()
73
+ es = NamedEntitySet(ib, entity_set)
74
+ page = await es.query(
75
+ top=top,
76
+ skip=skip,
77
+ select=select.split(",") if select else None,
78
+ odata_filter=odata_filter,
79
+ orderby=orderby,
80
+ inlinecount=inlinecount,
81
+ )
82
+ payload: dict[str, Any] = {
83
+ "entity_set": entity_set,
84
+ "value": page.value,
85
+ "count": len(page.value),
86
+ }
87
+ if inlinecount and page.count is not None:
88
+ payload["inlinecount"] = page.count
89
+ return payload
90
+
91
+
92
+ async def get_entity(
93
+ entity_set: str,
94
+ ref_key: str,
95
+ *,
96
+ select: str | None = None,
97
+ ) -> dict[str, Any]:
98
+ ib = await get_infobase()
99
+ es = NamedEntitySet(ib, entity_set)
100
+ record = await es.get(
101
+ ref_key,
102
+ select=select.split(",") if select else None,
103
+ )
104
+ return {"entity_set": entity_set, "ref_key": ref_key, "record": record}
105
+
106
+
107
+ async def get_metadata(*, raw_xml: bool = False) -> dict[str, Any]:
108
+ ib = await get_infobase()
109
+ if raw_xml:
110
+ xml = await ib.metadata()
111
+ truncated = len(xml) > _METADATA_XML_LIMIT
112
+ return {
113
+ "raw_xml": xml[:_METADATA_XML_LIMIT],
114
+ "length": len(xml),
115
+ "truncated": truncated,
116
+ }
117
+
118
+ names = await ib.entity_sets()
119
+ sample = names[:10]
120
+ return {
121
+ "entity_set_count": len(names),
122
+ "sample_entity_sets": sample,
123
+ "odata_root": ib.root,
124
+ }
125
+
126
+
127
+ async def resource_entity_sets() -> str:
128
+ ib = await get_infobase()
129
+ names = await ib.entity_sets()
130
+ lines = [f"{index + 1}. {name}" for index, name in enumerate(names)]
131
+ return "1C OData entity sets:\n" + "\n".join(lines)
132
+
133
+
134
+ async def resource_metadata() -> str:
135
+ ib = await get_infobase()
136
+ xml = await ib.metadata()
137
+ if len(xml) > _METADATA_XML_LIMIT:
138
+ return xml[:_METADATA_XML_LIMIT] + f"\n\n... truncated ({len(xml)} bytes total)"
139
+ return xml
@@ -0,0 +1,335 @@
1
+ Metadata-Version: 2.4
2
+ Name: python-1c-mcp
3
+ Version: 0.1.0
4
+ Summary: Read-only MCP server for 1C:Enterprise standard OData (8.3.5+)
5
+ Author-email: Artem Gulyaev <itsuppartem@yandex.ru>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/itsuppartem/python_1c_mcp
8
+ Project-URL: Repository, https://github.com/itsuppartem/python_1c_mcp
9
+ Project-URL: Issues, https://github.com/itsuppartem/python_1c_mcp/issues
10
+ Keywords: 1c,odata,mcp,1c-enterprise,model-context-protocol
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Topic :: Software Development :: Libraries
16
+ Requires-Python: >=3.10
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: python-1c-odata>=0.6.0
20
+ Requires-Dist: mcp>=2.0
21
+ Provides-Extra: dev
22
+ Requires-Dist: pytest>=8.0; extra == "dev"
23
+ Requires-Dist: pytest-asyncio>=0.24; extra == "dev"
24
+ Requires-Dist: ruff>=0.8; extra == "dev"
25
+ Requires-Dist: mypy>=1.13; extra == "dev"
26
+ Requires-Dist: aiohttp>=3.9.0; extra == "dev"
27
+ Dynamic: license-file
28
+
29
+ English | [Русский](#russkiy)
30
+
31
+ # python-1c-mcp
32
+
33
+ [![PyPI](https://img.shields.io/pypi/v/python-1c-mcp.svg)](https://pypi.org/project/python-1c-mcp/)
34
+ [![Python versions](https://img.shields.io/badge/python-3.10%20%7C%203.11%20%7C%203.12%20%7C%203.13-blue)](https://github.com/itsuppartem/python_1c_mcp)
35
+ [![CI](https://github.com/itsuppartem/python_1c_mcp/actions/workflows/test.yml/badge.svg)](https://github.com/itsuppartem/python_1c_mcp/actions/workflows/test.yml)
36
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/itsuppartem/python_1c_mcp/blob/main/LICENSE)
37
+
38
+ Read-only [Model Context Protocol](https://modelcontextprotocol.io/) server for **1C:Enterprise standard OData** (`standard.odata`, platform **8.3.5+**).
39
+
40
+ Built on [python-1c-odata](https://github.com/itsuppartem/python_1c_odata). Exposes schema discovery and OData queries to LLM agents in Claude Desktop, Cursor, and other MCP hosts.
41
+
42
+ Homepage / repo: https://github.com/itsuppartem/python_1c_mcp
43
+
44
+ ## Read-only scope
45
+
46
+ This server provides **read-only** access only:
47
+
48
+ - List and describe entity sets from `$metadata`
49
+ - Query entity sets (`$filter`, `$select`, `$top`, `$skip`, `$orderby`, `$inlinecount`)
50
+ - Fetch a single record by `Ref_Key`
51
+
52
+ There are **no** create, update, delete, post, or unpost tools.
53
+
54
+ **Honest limits:** standard OData 3.0 publication only. No 8.2, 7.7, SOAP, COM, or proprietary APIs. Oldest publication is 8.3.5 Atom (`ONEC_FORMAT=atom` or `auto`). JSON is the default (`8.3.6+`).
55
+
56
+ ## Install
57
+
58
+ ```bash
59
+ pip install python-1c-mcp
60
+ ```
61
+
62
+ Python 3.10+. Depends on `python-1c-odata` 0.6.0+ and `mcp` 2.0+. From a clone:
63
+
64
+ ```bash
65
+ git clone https://github.com/itsuppartem/python_1c_mcp.git
66
+ cd python_1c_mcp
67
+ pip install -e ".[dev]"
68
+ ```
69
+
70
+ ## Connect to 1C
71
+
72
+ This server talks to a **published standard OData** interface on 1C:Enterprise **8.3.5+**. It does not open Designer, the thick/thin client, SOAP `/ws/`, custom HTTP services (`/hs/`), COM, 8.2, or 7.7. If OData is not published, there is no other way for this MCP to “log into 1C”.
73
+
74
+ On the 1C side:
75
+
76
+ 1. Publish the infobase on the web server (Apache or IIS) from Designer: **Administration → Publish on web server**.
77
+ 2. Enable the standard OData interface for that publication (`enableStandardOData` / the OData checkbox). The service path is `/odata/standard.odata`.
78
+ 3. Create or pick a user who is allowed to use that publication (HTTP Basic). This is the web-service login, not an interactive Designer session.
79
+
80
+ URL shape from the four variables:
81
+
82
+ `{ONEC_SERVER}/{ONEC_INFOBASE}/odata/standard.odata`
83
+
84
+ Example: `ONEC_SERVER=http://1c.example`, `ONEC_INFOBASE=trade` → `http://1c.example/trade/odata/standard.odata`.
85
+
86
+ 8.3.5 publications speak Atom only — set `ONEC_FORMAT=atom` (or `auto`). 8.3.6+ can use the default JSON.
87
+
88
+ Auth is HTTP Basic: `ONEC_USER` / `ONEC_PASSWORD` (or `user:pass@` inside `ONEC_URL`). Then add the MCP JSON below in Cursor or Claude Desktop.
89
+
90
+ ## Connection (environment variables)
91
+
92
+ | Variable | Required | Description |
93
+ |----------|----------|-------------|
94
+ | `ONEC_SERVER` | Yes* | Server base URL, e.g. `http://1c.example` |
95
+ | `ONEC_INFOBASE` | Yes* | Publication name, e.g. `trade` |
96
+ | `ONEC_USER` | Yes* | OData user |
97
+ | `ONEC_PASSWORD` | Yes* | OData password |
98
+ | `ONEC_URL` | Alt. | Single URL: `http://user:pass@host/publication` (overrides the four vars above) |
99
+ | `ONEC_FORMAT` | No | Response format: `json` (default), `atom`, or `auto` |
100
+ | `ONEC_DEBUG` | No | If `true` / `1` / `yes` / `on`, log HTTP requests to stderr |
101
+
102
+ \* Either set `ONEC_URL` **or** all four of `ONEC_SERVER`, `ONEC_INFOBASE`, `ONEC_USER`, `ONEC_PASSWORD`.
103
+
104
+ The server validates configuration at startup and exits with a clear stderr message if settings are missing.
105
+
106
+ ## MCP configuration
107
+
108
+ ### Claude Desktop / Cursor
109
+
110
+ ```json
111
+ {
112
+ "mcpServers": {
113
+ "1c-odata": {
114
+ "command": "python",
115
+ "args": ["-m", "python_1c_mcp.server"],
116
+ "env": {
117
+ "ONEC_SERVER": "http://1c.example",
118
+ "ONEC_INFOBASE": "trade",
119
+ "ONEC_USER": "odata_user",
120
+ "ONEC_PASSWORD": "secret"
121
+ }
122
+ }
123
+ }
124
+ }
125
+ ```
126
+
127
+ Alternatively, use the console script:
128
+
129
+ ```json
130
+ {
131
+ "mcpServers": {
132
+ "1c-odata": {
133
+ "command": "python-1c-mcp",
134
+ "env": {
135
+ "ONEC_URL": "http://odata_user:secret@1c.example/trade"
136
+ }
137
+ }
138
+ }
139
+ }
140
+ ```
141
+
142
+ ## Tools
143
+
144
+ | Tool | Parameters | Description |
145
+ |------|------------|-------------|
146
+ | `list_entity_sets` | — | All entity set names from `$metadata` (truncated after 500) |
147
+ | `describe_entity_set` | `entity_set` | Keys, properties, navigation for one set (e.g. `Catalog_Товары`) |
148
+ | `odata_query` | `entity_set`, `odata_filter`, `select`, `top`, `skip`, `orderby`, `inlinecount` | Read-only collection query. `top` default 20, max 100 |
149
+ | `get_entity` | `entity_set`, `ref_key`, `select` | Single record by `Ref_Key` GUID |
150
+ | `get_metadata` | `raw_xml` | Summary (count + sample names) or truncated raw `$metadata` XML |
151
+
152
+ ## Resources
153
+
154
+ | URI | Description |
155
+ |-----|-------------|
156
+ | `1c://entity-sets` | Plain-text list of entity set names |
157
+ | `1c://metadata` | `$metadata` XML (truncated if large) |
158
+
159
+ ## What is still missing
160
+
161
+ | Missing | Notes |
162
+ | --- | --- |
163
+ | Write tools | no create / edit / delete / post / unpost — this package is read-only |
164
+ | 8.2 / 7.7 / SOAP / COM / `/hs/` / OData 4 | out of scope. Oldest publication we speak is 8.3.5 Atom |
165
+
166
+ ## Development
167
+
168
+ ```bash
169
+ python -m venv .venv
170
+ source .venv/bin/activate
171
+ pip install -e ".[dev]"
172
+ pytest
173
+ ruff check src tests
174
+ mypy src
175
+ ```
176
+
177
+ ## License
178
+
179
+ MIT — Artem Gulyaev
180
+
181
+ ---
182
+
183
+ <h2 id="russkiy">Русский</h2>
184
+
185
+ # python-1c-mcp
186
+
187
+ [English](#python-1c-mcp) | Русский
188
+
189
+ [![PyPI](https://img.shields.io/pypi/v/python-1c-mcp.svg)](https://pypi.org/project/python-1c-mcp/)
190
+ [![Python versions](https://img.shields.io/badge/python-3.10%20%7C%203.11%20%7C%203.12%20%7C%203.13-blue)](https://github.com/itsuppartem/python_1c_mcp)
191
+ [![CI](https://github.com/itsuppartem/python_1c_mcp/actions/workflows/test.yml/badge.svg)](https://github.com/itsuppartem/python_1c_mcp/actions/workflows/test.yml)
192
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/itsuppartem/python_1c_mcp/blob/main/LICENSE)
193
+
194
+ Сервер [Model Context Protocol](https://modelcontextprotocol.io/) **только для чтения** стандартного OData **1С:Предприятие** (`standard.odata`, платформа **8.3.5+**).
195
+
196
+ Собран на [python-1c-odata](https://github.com/itsuppartem/python_1c_odata). Отдаёт агентам LLM в Claude Desktop, Cursor и других MCP-хостах схему и запросы OData.
197
+
198
+ Репозиторий: https://github.com/itsuppartem/python_1c_mcp
199
+
200
+ ## Область только чтения
201
+
202
+ Сервер даёт доступ **только на чтение**:
203
+
204
+ - Список и описание наборов сущностей из `$metadata`
205
+ - Запросы к наборам (`$filter`, `$select`, `$top`, `$skip`, `$orderby`, `$inlinecount`)
206
+ - Одна запись по `Ref_Key`
207
+
208
+ Инструментов создания, изменения, удаления, проведения и отмены проведения **нет**.
209
+
210
+ **Честные границы:** только стандартная публикация OData 3.0. Нет 8.2, 7.7, SOAP, COM и закрытых API. Самая старая публикация — Atom 8.3.5 (`ONEC_FORMAT=atom` или `auto`). По умолчанию JSON (`8.3.6+`).
211
+
212
+ ## Установка
213
+
214
+ ```bash
215
+ pip install python-1c-mcp
216
+ ```
217
+
218
+ Нужен Python 3.10+. Зависимости: `python-1c-odata` 0.6.0+ и `mcp` 2.0+. Из клона:
219
+
220
+ ```bash
221
+ git clone https://github.com/itsuppartem/python_1c_mcp.git
222
+ cd python_1c_mcp
223
+ pip install -e ".[dev]"
224
+ ```
225
+
226
+ ## Подключение к 1С
227
+
228
+ Сервер ходит в **опубликованный стандартный OData** на 1С:Предприятие **8.3.5+**. Он не открывает Конфигуратор, толстый/тонкий клиент, SOAP `/ws/`, произвольные HTTP-сервисы (`/hs/`), COM, 8.2 и 7.7. Если OData не опубликован, другим способом «войти в 1С» этот MCP не умеет.
229
+
230
+ На стороне 1С:
231
+
232
+ 1. Опубликуйте информационную базу на веб-сервере (Apache или IIS) из Конфигуратора: **Администрирование → Публикация на веб-сервере**.
233
+ 2. Включите стандартный интерфейс OData у этой публикации (`enableStandardOData` / флажок OData). Путь сервиса — `/odata/standard.odata`.
234
+ 3. Заведите или выберите пользователя с правом на эту публикацию (HTTP Basic). Это логин веб-сервиса, не интерактивный сеанс Конфигуратора.
235
+
236
+ Форма URL из четырёх переменных:
237
+
238
+ `{ONEC_SERVER}/{ONEC_INFOBASE}/odata/standard.odata`
239
+
240
+ Пример: `ONEC_SERVER=http://1c.example`, `ONEC_INFOBASE=trade` → `http://1c.example/trade/odata/standard.odata`.
241
+
242
+ Публикации 8.3.5 говорят только Atom — задайте `ONEC_FORMAT=atom` (или `auto`). С 8.3.6 можно оставить JSON по умолчанию.
243
+
244
+ Авторизация — HTTP Basic: `ONEC_USER` / `ONEC_PASSWORD` (или `user:pass@` внутри `ONEC_URL`). Затем добавьте JSON MCP ниже в Cursor или Claude Desktop.
245
+
246
+ ## Подключение (переменные окружения)
247
+
248
+ | Переменная | Обязательна | Описание |
249
+ |------------|-------------|----------|
250
+ | `ONEC_SERVER` | Да* | Базовый URL сервера, например `http://1c.example` |
251
+ | `ONEC_INFOBASE` | Да* | Имя публикации, например `trade` |
252
+ | `ONEC_USER` | Да* | Пользователь OData |
253
+ | `ONEC_PASSWORD` | Да* | Пароль OData |
254
+ | `ONEC_URL` | Альтернатива | Один URL: `http://user:pass@host/publication` (перекрывает четыре переменные выше) |
255
+ | `ONEC_FORMAT` | Нет | Формат ответа: `json` (по умолчанию), `atom` или `auto` |
256
+ | `ONEC_DEBUG` | Нет | Если `true` / `1` / `yes` / `on`, HTTP-запросы пишутся в stderr |
257
+
258
+ \* Задайте либо `ONEC_URL`, **либо** все четыре: `ONEC_SERVER`, `ONEC_INFOBASE`, `ONEC_USER`, `ONEC_PASSWORD`.
259
+
260
+ Сервер проверяет настройки при старте и выходит с понятным сообщением в stderr, если чего-то не хватает.
261
+
262
+ ## Настройка MCP
263
+
264
+ ### Claude Desktop / Cursor
265
+
266
+ ```json
267
+ {
268
+ "mcpServers": {
269
+ "1c-odata": {
270
+ "command": "python",
271
+ "args": ["-m", "python_1c_mcp.server"],
272
+ "env": {
273
+ "ONEC_SERVER": "http://1c.example",
274
+ "ONEC_INFOBASE": "trade",
275
+ "ONEC_USER": "odata_user",
276
+ "ONEC_PASSWORD": "secret"
277
+ }
278
+ }
279
+ }
280
+ }
281
+ ```
282
+
283
+ Либо консольный скрипт:
284
+
285
+ ```json
286
+ {
287
+ "mcpServers": {
288
+ "1c-odata": {
289
+ "command": "python-1c-mcp",
290
+ "env": {
291
+ "ONEC_URL": "http://odata_user:secret@1c.example/trade"
292
+ }
293
+ }
294
+ }
295
+ }
296
+ ```
297
+
298
+ ## Инструменты
299
+
300
+ | Инструмент | Параметры | Описание |
301
+ |------------|-----------|----------|
302
+ | `list_entity_sets` | — | Все имена наборов из `$metadata` (обрезка после 500) |
303
+ | `describe_entity_set` | `entity_set` | Ключи, свойства, навигация одного набора (например `Catalog_Товары`) |
304
+ | `odata_query` | `entity_set`, `odata_filter`, `select`, `top`, `skip`, `orderby`, `inlinecount` | Запрос коллекции только на чтение. `top` по умолчанию 20, максимум 100 |
305
+ | `get_entity` | `entity_set`, `ref_key`, `select` | Одна запись по GUID `Ref_Key` |
306
+ | `get_metadata` | `raw_xml` | Сводка (число + примеры имён) или обрезанный XML `$metadata` |
307
+
308
+ ## Ресурсы
309
+
310
+ | URI | Описание |
311
+ |-----|----------|
312
+ | `1c://entity-sets` | Текстовый список имён наборов |
313
+ | `1c://metadata` | XML `$metadata` (обрезается, если большой) |
314
+
315
+ ## Чего нет
316
+
317
+ | Нет | Комментарий |
318
+ | --- | --- |
319
+ | Инструменты записи | нет create / edit / delete / post / unpost — пакет только для чтения |
320
+ | 8.2 / 7.7 / SOAP / COM / `/hs/` / OData 4 | вне задачи. Самая старая публикация — Atom 8.3.5 |
321
+
322
+ ## Разработка
323
+
324
+ ```bash
325
+ python -m venv .venv
326
+ source .venv/bin/activate
327
+ pip install -e ".[dev]"
328
+ pytest
329
+ ruff check src tests
330
+ mypy src
331
+ ```
332
+
333
+ ## Лицензия
334
+
335
+ MIT — Артём Гуляев
@@ -0,0 +1,12 @@
1
+ python_1c_mcp/__init__.py,sha256=1j7FoDdgNyIVffC_z2uxNwkcOdUSSPo8aAS8lqb16q4,84
2
+ python_1c_mcp/connection.py,sha256=v_AIX22EVqFxsfmVtk4Ckdj6pW7QSYE0yebS4PHViys,4142
3
+ python_1c_mcp/entity_set.py,sha256=FVp5Lo9rG7J8dyNbdWhQ-lqdXquAiAkxTJ3eWNMfnqg,535
4
+ python_1c_mcp/server.py,sha256=O-yaT1AuViANf1gssN0bpih0gtj5YeK0Y6xNLB-d7OY,3877
5
+ python_1c_mcp/tools/__init__.py,sha256=xL1JPdHaZaqAo1x3XYvosiQIxyaOEWBXiIgawZUbWgY,31
6
+ python_1c_mcp/tools/handlers.py,sha256=0mjQ2TQZB5_0m7vNcI2Aoo7ToywSSQLdRatPjH_L5M8,3842
7
+ python_1c_mcp-0.1.0.dist-info/licenses/LICENSE,sha256=EBmfCEuDqfn65lOu87uo3uJv22P2p_XF27fgEY2CR-4,1070
8
+ python_1c_mcp-0.1.0.dist-info/METADATA,sha256=9a1mtlByejamEhbUApZZ09eCmKpZbez4s2_0MKujQPY,14126
9
+ python_1c_mcp-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
10
+ python_1c_mcp-0.1.0.dist-info/entry_points.txt,sha256=sWY8256hhfku4A-hpJwpeJNU1UBSLlsjfKq7k2otjfs,60
11
+ python_1c_mcp-0.1.0.dist-info/top_level.txt,sha256=mlnenEmsL4rO7pbsDxssTCP4DVOrFRnuPgRZJ4rziq4,14
12
+ python_1c_mcp-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ python-1c-mcp = python_1c_mcp.server:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Artem Gulyaev
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ python_1c_mcp