crowdsec-local-mcp 0.0.2__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.
Files changed (31) hide show
  1. crowdsec_local_mcp/__init__.py +5 -0
  2. crowdsec_local_mcp/__main__.py +24 -0
  3. crowdsec_local_mcp/compose/waf-test/.gitignore +3 -0
  4. crowdsec_local_mcp/compose/waf-test/crowdsec/acquis.d/appsec.yaml +8 -0
  5. crowdsec_local_mcp/compose/waf-test/crowdsec/appsec-configs/mcp-appsec.yaml.template +8 -0
  6. crowdsec_local_mcp/compose/waf-test/crowdsec/init-bouncer.sh +29 -0
  7. crowdsec_local_mcp/compose/waf-test/docker-compose.yml +68 -0
  8. crowdsec_local_mcp/compose/waf-test/nginx/Dockerfile +67 -0
  9. crowdsec_local_mcp/compose/waf-test/nginx/crowdsec/crowdsec-openresty-bouncer.conf +25 -0
  10. crowdsec_local_mcp/compose/waf-test/nginx/nginx.conf +25 -0
  11. crowdsec_local_mcp/compose/waf-test/nginx/site-enabled/default-site.conf +15 -0
  12. crowdsec_local_mcp/compose/waf-test/rules/.gitkeep +0 -0
  13. crowdsec_local_mcp/compose/waf-test/rules/base-config.yaml +11 -0
  14. crowdsec_local_mcp/mcp_core.py +151 -0
  15. crowdsec_local_mcp/mcp_scenarios.py +380 -0
  16. crowdsec_local_mcp/mcp_waf.py +1170 -0
  17. crowdsec_local_mcp/prompts/prompt-scenario-deploy.txt +27 -0
  18. crowdsec_local_mcp/prompts/prompt-scenario-examples.txt +237 -0
  19. crowdsec_local_mcp/prompts/prompt-scenario.txt +84 -0
  20. crowdsec_local_mcp/prompts/prompt-waf-deploy.txt +118 -0
  21. crowdsec_local_mcp/prompts/prompt-waf-examples.txt +401 -0
  22. crowdsec_local_mcp/prompts/prompt-waf.txt +343 -0
  23. crowdsec_local_mcp/setup_cli.py +306 -0
  24. crowdsec_local_mcp/yaml-schemas/appsec_rules_schema.yaml +343 -0
  25. crowdsec_local_mcp/yaml-schemas/scenario_schema.yaml +591 -0
  26. crowdsec_local_mcp-0.0.2.dist-info/METADATA +74 -0
  27. crowdsec_local_mcp-0.0.2.dist-info/RECORD +31 -0
  28. crowdsec_local_mcp-0.0.2.dist-info/WHEEL +5 -0
  29. crowdsec_local_mcp-0.0.2.dist-info/entry_points.txt +3 -0
  30. crowdsec_local_mcp-0.0.2.dist-info/licenses/LICENSE +21 -0
  31. crowdsec_local_mcp-0.0.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,5 @@
1
+ """CrowdSec MCP package."""
2
+
3
+ from .mcp_core import main
4
+
5
+ __all__ = ["main"]
@@ -0,0 +1,24 @@
1
+ #!/usr/bin/env python3
2
+
3
+ # Use `uv run --project . <command>` to run this module directly for testing.
4
+
5
+ import asyncio
6
+
7
+ from .mcp_core import LOGGER, main
8
+
9
+ # Import modules for their registration side effects.
10
+ from . import mcp_waf # noqa: F401
11
+
12
+ try:
13
+ from . import mcp_scenarios # noqa: F401
14
+ except ModuleNotFoundError:
15
+ LOGGER.warning("Scenario module not available; scenario tools disabled")
16
+
17
+
18
+ def run() -> None:
19
+ """Entry-point used by console scripts."""
20
+ asyncio.run(main())
21
+
22
+
23
+ if __name__ == "__main__":
24
+ run()
@@ -0,0 +1,3 @@
1
+ # Generated at runtime by the MCP integration.
2
+ rules/current-rule.yaml
3
+ crowdsec/appsec-configs/mcp-appsec.yaml
@@ -0,0 +1,8 @@
1
+ # Acquisition file registering the MCP-generated AppSec configuration.
2
+ appsec_configs:
3
+ - mcp-appsec
4
+ labels:
5
+ type: appsec
6
+ listen_addr: 0.0.0.0:7422
7
+ source: appsec
8
+ name: myAppSecComponent
@@ -0,0 +1,8 @@
1
+ name: mcp-appsec
2
+ default_remediation: ban
3
+ inband_rules:
4
+ # Keep the CrowdSec base config to ensure essential protections remain active.
5
+ - crowdsecurity/base-config
6
+ # The MCP tooling copies the user rule into the custom directory as current-rule.yaml
7
+ ## XXX FIXME : make this a variable :)
8
+ - __PLACEHOLDER_FOR_USER_RULE__
@@ -0,0 +1,29 @@
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+
4
+ API_KEY="mcp-nginx-bouncer-test-key"
5
+ BOUNCER_NAME="mcp-nginx-bouncer"
6
+
7
+ /bin/bash /docker_start.sh "$@" &
8
+ PID=$!
9
+ trap 'kill "$PID" 2>/dev/null || true' EXIT
10
+
11
+ for _ in $(seq 1 90); do
12
+ if cscli lapi status >/dev/null 2>&1; then
13
+ break
14
+ fi
15
+ sleep 2;
16
+ done
17
+
18
+ if ! cscli lapi status >/dev/null 2>&1; then
19
+ echo "CrowdSec LAPI did not become ready in time" >&2
20
+ wait "$PID"
21
+ exit 1
22
+ fi
23
+
24
+ cscli bouncers delete "$BOUNCER_NAME" >/dev/null 2>&1 || true
25
+ cscli bouncers add "$BOUNCER_NAME" -k "$API_KEY"
26
+
27
+ trap - EXIT
28
+ wait "$PID"
29
+ exit $?
@@ -0,0 +1,68 @@
1
+ version: "3.9"
2
+
3
+ services:
4
+ crowdsec:
5
+ image: crowdsecurity/crowdsec:latest
6
+ hostname: crowdsec
7
+ container_name: crowdsec-appsec
8
+ restart: "no"
9
+ entrypoint:
10
+ - /bin/bash
11
+ - /usr/local/bin/init-bouncer.sh
12
+ environment:
13
+ # Ensure the local API stays accessible for the nginx bouncer.
14
+ - DISABLE_LOCAL_API=0
15
+ - DISABLE_ONLINE_API=1
16
+ # Turn on AppSec mode inside the CrowdSec container.
17
+ - ENABLE_APPSEC=1
18
+ volumes:
19
+ # Persist CrowdSec data (buckets, alerts, etc.) between restarts.
20
+ - crowdsec-data:/var/lib/crowdsec/data
21
+ # Allow templated acquisition and AppSec config overrides without replacing the whole /etc/crowdsec tree.
22
+ - ./crowdsec/acquis.d/appsec.yaml:/etc/crowdsec/acquis.d/appsec-mcp.yaml:ro
23
+ - ./crowdsec/appsec-configs/mcp-appsec.yaml:/etc/crowdsec/appsec-configs/mcp-appsec.yaml:ro
24
+ - ./crowdsec/init-bouncer.sh:/usr/local/bin/init-bouncer.sh:ro
25
+ # The MCP tooling will drop the user-provided rule in this folder as current-rule.yaml
26
+ - ./rules:/etc/crowdsec/appsec-rules/custom
27
+ ports:
28
+ - "18080:8080" # LAPI (use non-default host port to avoid conflicts)
29
+ - "17422:7422" # AppSec Live mode (non-default host port)
30
+ networks:
31
+ - waf-net
32
+
33
+ nginx:
34
+ build:
35
+ context: ./nginx
36
+ container_name: nginx-appsec
37
+ restart: "no"
38
+ depends_on:
39
+ - crowdsec
40
+ - backend
41
+ ports:
42
+ - "8081:80"
43
+ command:
44
+ - openresty
45
+ - -g
46
+ - 'daemon off;'
47
+ volumes:
48
+ - ./nginx/nginx.conf:/usr/local/openresty/nginx/conf/nginx.conf:ro
49
+ # Site config enabling the CrowdSec module and proxying to the backend.
50
+ - ./nginx/site-enabled:/usr/local/openresty/nginx/conf/site-enabled:ro
51
+ # Override the bouncer configuration shipped in the image with the harness version.
52
+ - ./nginx/crowdsec/crowdsec-openresty-bouncer.conf:/etc/crowdsec/bouncers/crowdsec-openresty-bouncer.conf:ro
53
+ networks:
54
+ - waf-net
55
+
56
+ backend:
57
+ image: nginxdemos/hello:latest
58
+ container_name: app-backend
59
+ restart: unless-stopped
60
+ networks:
61
+ - waf-net
62
+
63
+ volumes:
64
+ crowdsec-data:
65
+
66
+ networks:
67
+ waf-net:
68
+ driver: bridge
@@ -0,0 +1,67 @@
1
+
2
+ FROM ubuntu:24.04
3
+
4
+ # Install dependencies
5
+ RUN apt-get update && apt-get install -y \
6
+ git \
7
+ make \
8
+ software-properties-common \
9
+ wget \
10
+ gnupg \
11
+ ca-certificates \
12
+ gettext \
13
+ curl
14
+
15
+ RUN wget -O - https://openresty.org/package/pubkey.gpg | apt-key add -
16
+ RUN echo "deb http://openresty.org/package/ubuntu $(lsb_release -sc) main"| tee /etc/apt/sources.list.d/openresty.list
17
+ RUN curl -s https://install.crowdsec.net | bash
18
+
19
+ RUN apt update
20
+
21
+ RUN apt install -y openresty openresty-opm gettext-base
22
+
23
+ RUN apt install -y crowdsec-openresty-bouncer
24
+
25
+
26
+
27
+ EXPOSE 80
28
+
29
+
30
+ # # Install the bouncer
31
+ # COPY build.sh /build.sh
32
+ # COPY start.sh /start.sh
33
+
34
+ # RUN chmod +x /build.sh && /build.sh
35
+ # RUN chmod +x /start.sh
36
+
37
+ # # Set the script as the entrypoint
38
+ # ENTRYPOINT ["/start.sh"]
39
+
40
+
41
+
42
+ # FROM debian:bookworm
43
+
44
+ # ENV DEBIAN_FRONTEND=noninteractive
45
+
46
+ # # Install nginx with Lua module support and prerequisites for the CrowdSec nginx bouncer.
47
+ # RUN set -eux; \
48
+ # apt-get update; \
49
+ # apt-get install -y --no-install-recommends \
50
+ # ca-certificates \
51
+ # curl \
52
+ # gnupg2 \
53
+ # iproute2 \
54
+ # libnginx-mod-http-lua \
55
+ # lsb-release \
56
+ # nginx \
57
+ # procps; \
58
+ # curl -s https://packagecloud.io/install/repositories/crowdsec/crowdsec/script.deb.sh | bash; \
59
+ # apt-get install -y --no-install-recommends crowdsec-nginx-bouncer; \
60
+ # rm -rf /var/lib/apt/lists/*
61
+
62
+ # # Prepare directories that will receive bind mounts at runtime.
63
+ # RUN mkdir -p /etc/nginx/conf.d /etc/nginx/crowdsec
64
+
65
+ # EXPOSE 80
66
+
67
+ # CMD ["nginx", "-g", "daemon off;"]
@@ -0,0 +1,25 @@
1
+ API_URL=http://crowdsec:8080
2
+ API_KEY=mcp-nginx-bouncer-test-key
3
+ BOUNCING_ON_TYPE=all
4
+ FALLBACK_REMEDIATION=ban
5
+ MODE=stream
6
+ REQUEST_TIMEOUT=1000
7
+ EXCLUDE_LOCATION=
8
+ ENABLE_INTERNAL=false
9
+ CACHE_EXPIRATION=1
10
+ UPDATE_FREQUENCY=10
11
+ BAN_TEMPLATE_PATH=/var/lib/crowdsec/lua/templates/ban.html
12
+ REDIRECT_LOCATION=
13
+ RET_CODE=
14
+ CAPTCHA_PROVIDER=
15
+ SECRET_KEY=
16
+ SITE_KEY=
17
+ CAPTCHA_TEMPLATE_PATH=/var/lib/crowdsec/lua/templates/captcha.html
18
+ CAPTCHA_EXPIRATION=3600
19
+ APPSEC_URL=http://crowdsec:7422
20
+ APPSEC_FAILURE_ACTION=passthrough
21
+ APPSEC_CONNECT_TIMEOUT=100
22
+ APPSEC_SEND_TIMEOUT=100
23
+ APPSEC_PROCESS_TIMEOUT=1000
24
+ ALWAYS_SEND_TO_APPSEC=false
25
+ SSL_VERIFY=true
@@ -0,0 +1,25 @@
1
+
2
+ worker_processes auto;
3
+
4
+ error_log /dev/stderr info;
5
+ pid /tmp/nginx.pid;
6
+
7
+
8
+ events {
9
+ worker_connections 1024;
10
+ }
11
+
12
+ http {
13
+ resolver 127.0.0.11;
14
+
15
+ include /usr/local/openresty/nginx/conf/mime.types;
16
+ default_type application/octet-stream;
17
+
18
+ sendfile on;
19
+ keepalive_timeout 65;
20
+
21
+ access_log /dev/stdout;
22
+
23
+ include /usr/local/openresty/nginx/conf/conf.d/*.conf;
24
+ include /usr/local/openresty/nginx/conf/site-enabled/*.conf;
25
+ }
@@ -0,0 +1,15 @@
1
+ # Auto-generated by MCP test harness. Route requests through AppSec and the CrowdSec bouncer.
2
+ upstream backend_app {
3
+ server backend:80;
4
+ }
5
+
6
+ server {
7
+ listen 80;
8
+ server_name _;
9
+
10
+ location / {
11
+ proxy_pass http://backend_app;
12
+ proxy_set_header Host $host;
13
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
14
+ }
15
+ }
File without changes
@@ -0,0 +1,11 @@
1
+ name: crowdsecurity/base-config
2
+ #### This file is intended to provide a basic configuration for coraza:
3
+ #### - Set the body processors based on the content-type
4
+
5
+ seclang_rules:
6
+ - Secrule REQUEST_HEADERS:Content-Type "@rx ^application/x-www-form-urlencoded" "id:100,phase:1,pass,nolog,noauditlog,ctl:requestBodyProcessor=URLENCODED"
7
+ - Secrule REQUEST_HEADERS:Content-Type "@rx ^multipart/form-data" "id:101,phase:1,pass,nolog,noauditlog,ctl:requestBodyProcessor=MULTIPART"
8
+ - Secrule REQUEST_HEADERS:Content-Type "@rx ^application/xml" "id:102,phase:1,pass,nolog,noauditlog,ctl:requestBodyProcessor=XML"
9
+ - Secrule REQUEST_HEADERS:Content-Type "@rx ^application/json" "id:103,phase:1,pass,nolog,noauditlog,ctl:requestBodyProcessor=JSON"
10
+ - Secrule REQUEST_HEADERS:Content-Type "@rx ^text/xml" "id:104,phase:1,pass,nolog,noauditlog,ctl:requestBodyProcessor=XML"
11
+ - SecRule REQBODY_PROCESSOR "!@rx (?:URLENCODED|MULTIPART|XML|JSON)" "id:105,phase:1,pass,nolog,noauditlog,ctl:requestBodyProcessor=RAW" #Use our custom RAW body processor, just to have REQUEST_BODY set
@@ -0,0 +1,151 @@
1
+ import asyncio
2
+ import logging
3
+ import tempfile
4
+ from collections import OrderedDict
5
+ from pathlib import Path
6
+ from typing import Any, Callable, Dict, List, Optional
7
+
8
+ import mcp.server.stdio
9
+ import mcp.types as types
10
+ from mcp.server import NotificationOptions, Server
11
+ from mcp.server.models import InitializationOptions
12
+
13
+ SCRIPT_DIR = Path(__file__).parent
14
+ PROMPTS_DIR = SCRIPT_DIR / "prompts"
15
+ LOG_FILE_PATH = Path(tempfile.gettempdir()) / "crowdsec-mcp.log"
16
+
17
+
18
+ def _configure_logger() -> logging.Logger:
19
+ """Configure and return the module-level logger."""
20
+ LOG_FILE_PATH.parent.mkdir(parents=True, exist_ok=True)
21
+
22
+ logger = logging.getLogger("crowdsec-mcp")
23
+ if logger.handlers:
24
+ return logger
25
+
26
+ logger.setLevel(logging.INFO)
27
+ handler = logging.FileHandler(LOG_FILE_PATH, encoding="utf-8")
28
+ formatter = logging.Formatter(
29
+ "%(asctime)s [%(levelname)s] %(name)s: %(message)s"
30
+ )
31
+ handler.setFormatter(formatter)
32
+ logger.addHandler(handler)
33
+ logger.propagate = False
34
+ return logger
35
+
36
+
37
+ LOGGER = _configure_logger()
38
+ server = Server("crowdsec-prompt-server")
39
+
40
+ ToolHandler = Callable[[Optional[Dict[str, Any]]], List[types.TextContent]]
41
+ ResourceReader = Callable[[], str]
42
+
43
+
44
+ class MCPRegistry:
45
+ """Central registry for tool and resource integrations."""
46
+
47
+ def __init__(self) -> None:
48
+ self._tool_handlers: Dict[str, ToolHandler] = {}
49
+ self._tools: "OrderedDict[str, types.Tool]" = OrderedDict()
50
+ self._resources: "OrderedDict[str, types.Resource]" = OrderedDict()
51
+ self._resource_readers: Dict[str, ResourceReader] = {}
52
+
53
+ def register_tools(
54
+ self,
55
+ handlers: Dict[str, ToolHandler],
56
+ tool_definitions: List[types.Tool],
57
+ ) -> None:
58
+ for name, handler in handlers.items():
59
+ if name in self._tool_handlers:
60
+ raise ValueError(f"Tool handler already registered for '{name}'")
61
+ self._tool_handlers[name] = handler
62
+
63
+ for tool in tool_definitions:
64
+ if tool.name in self._tools:
65
+ raise ValueError(f"Tool definition already registered for '{tool.name}'")
66
+ self._tools[tool.name] = tool
67
+
68
+ def register_resources(
69
+ self,
70
+ resources: List[types.Resource],
71
+ readers: Dict[str, ResourceReader],
72
+ ) -> None:
73
+ for resource in resources:
74
+ if resource.uri in self._resources:
75
+ raise ValueError(f"Resource already registered for '{resource.uri}'")
76
+ self._resources[resource.uri] = resource
77
+
78
+ for uri, reader in readers.items():
79
+ if uri in self._resource_readers:
80
+ raise ValueError(f"Resource reader already registered for '{uri}'")
81
+ self._resource_readers[uri] = reader
82
+
83
+ @property
84
+ def tools(self) -> List[types.Tool]:
85
+ return list(self._tools.values())
86
+
87
+ @property
88
+ def resources(self) -> List[types.Resource]:
89
+ return list(self._resources.values())
90
+
91
+ def get_tool_handler(self, name: str) -> ToolHandler:
92
+ try:
93
+ return self._tool_handlers[name]
94
+ except KeyError as exc:
95
+ raise ValueError(f"Unknown tool: {name}") from exc
96
+
97
+ def get_resource_reader(self, uri: str) -> ResourceReader:
98
+ try:
99
+ return self._resource_readers[uri]
100
+ except KeyError as exc:
101
+ raise ValueError(f"Unknown resource: {uri}") from exc
102
+
103
+
104
+ REGISTRY = MCPRegistry()
105
+
106
+
107
+ @server.list_tools()
108
+ async def handle_list_tools() -> List[types.Tool]:
109
+ LOGGER.info("Listing available tools")
110
+ return REGISTRY.tools
111
+
112
+
113
+ @server.call_tool()
114
+ async def handle_call_tool(
115
+ name: str, arguments: Optional[Dict[str, Any]]
116
+ ) -> List[types.TextContent]:
117
+ LOGGER.info("handle_call_tool invoked for tool '%s'", name)
118
+ handler = REGISTRY.get_tool_handler(name)
119
+ return handler(arguments)
120
+
121
+
122
+ @server.list_resources()
123
+ async def handle_list_resources() -> List[types.Resource]:
124
+ LOGGER.info("Listing available resources")
125
+ return REGISTRY.resources
126
+
127
+
128
+ @server.read_resource()
129
+ async def handle_read_resource(uri: str) -> str:
130
+ LOGGER.info("Reading resource content for %s", uri)
131
+ reader = REGISTRY.get_resource_reader(uri)
132
+ return reader()
133
+
134
+
135
+ async def main() -> None:
136
+ """Main entry point for the MCP server."""
137
+ LOGGER.info("Starting MCP stdio server")
138
+ async with mcp.server.stdio.stdio_server() as (read_stream, write_stream):
139
+ await server.run(
140
+ read_stream,
141
+ write_stream,
142
+ InitializationOptions(
143
+ server_name="crowdsec-prompt-server",
144
+ server_version="0.1.0",
145
+ capabilities=server.get_capabilities(
146
+ notification_options=NotificationOptions(),
147
+ experimental_capabilities={},
148
+ ),
149
+ ),
150
+ )
151
+ LOGGER.info("MCP stdio server stopped")