<tools>
  <tool name="python_action">
    <description>Perform Python actions using persistent interpreter sessions for cybersecurity tasks.</description>
    <details>Common Use Cases:
      - Security script development and testing (payload generation, exploit scripts)
      - Data analysis of security logs, network traffic, or vulnerability scans
      - Cryptographic operations and security tool automation
      - Interactive penetration testing workflows and proof-of-concept development
      - Processing security data formats (JSON, XML, CSV from security tools)
      - HTTP proxy interaction for web security testing (all proxy functions are pre-imported)

      Each session instance is PERSISTENT and maintains its own global and local namespaces
      until explicitly closed, allowing for multi-step security workflows and stateful computations.

      PROXY FUNCTIONS PRE-IMPORTED:
      All proxy action functions are automatically imported into every Python session, enabling
      seamless HTTP traffic analysis and web security testing

      This is particularly useful for:
      - Analyzing captured HTTP traffic during web application testing
      - Automating request manipulation and replay attacks
      - Building custom security testing workflows combining proxy data with Python analysis
      - Correlating multiple requests for advanced attack scenarios</details>
    <parameters>
      <parameter name="action" type="string" required="true">
        <description>The Python action to perform:     - new_session: Create a new Python interpreter session. This MUST be the first       action for each session.     - execute: Execute Python code in the specified session.     - close: Close the specified session instance.     - list_sessions: List all active Python sessions.</description>
      </parameter>
      <parameter name="code" type="string" required="false">
        <description>Required for 'new_session' (as initial code) and 'execute' actions. The Python code to execute.</description>
      </parameter>
      <parameter name="timeout" type="integer" required="false">
        <description>Maximum execution time in seconds for code execution. Applies to both 'new_session' (when initial code is provided) and 'execute' actions. Default is 30 seconds.</description>
      </parameter>
      <parameter name="session_id" type="string" required="false">
        <description>Unique identifier for the Python session. If not provided, uses the default session ID.</description>
      </parameter>
    </parameters>
    <returns type="Dict[str, Any]">
      <description>Response containing: - session_id: the ID of the session that was operated on - stdout: captured standard output from code execution (for execute action) - stderr: any error message if execution failed - result: string representation of the last expression result - execution_time: time taken to execute the code - message: status message about the action performed - Various session info depending on the action</description>
    </returns>
    <notes>
  Important usage rules:
      1. PERSISTENCE: Session instances remain active and maintain their state (variables,
         imports, function definitions) until explicitly closed with the 'close' action.
         This allows for multi-step workflows across multiple tool calls.
      2. MULTIPLE SESSIONS: You can run multiple Python sessions concurrently by using
         different session_id values. Each session operates independently with its own
         namespace.
      3. Session interaction MUST begin with 'new_session' action for each session instance.
      4. Only one action can be performed per call.
      5. CODE EXECUTION:
         - Both expressions and statements are supported
         - Expressions automatically return their result
         - Print statements and stdout are captured
         - Variables persist between executions in the same session
         - Imports, function definitions, etc. persist in the session
         - IMPORTANT (multiline): Put real line breaks in your code. Do NOT emit literal "\n" sequences — use actual newlines.
         - IPython magic commands are fully supported (%pip, %time, %whos, %%writefile, etc.)
         - Line magics (%) and cell magics (%%) work as expected
      6. CLOSE: Terminates the session completely and frees memory
      7. The Python sessions can operate concurrently with other tools. You may invoke
         terminal, browser, or other tools while maintaining active Python sessions.
      8. Each session has its own isolated namespace - variables in one session don't
         affect others.
    </notes>
    <examples>
  # Create new session for security analysis (default session)
      <function=python_action>
      <parameter=action>new_session</parameter>
      <parameter=code>import hashlib
      import base64
      import json
      print("Security analysis session started")</parameter>
      </function>

      <function=python_action>
      <parameter=action>execute</parameter>
      <parameter=code>import requests
url = "https://example.com"
resp = requests.get(url, timeout=10)
print(resp.status_code)</parameter>
      </function>

      # Analyze security data in the default session
      <function=python_action>
      <parameter=action>execute</parameter>
      <parameter=code>vulnerability_data = {"cve": "CVE-2024-1234", "severity": "high"}
      encoded_payload = base64.b64encode(json.dumps(vulnerability_data).encode())
      print(f"Encoded: {encoded_payload.decode()}")</parameter>
      </function>

      # Long running security scan with custom timeout
      <function=python_action>
      <parameter=action>execute</parameter>
      <parameter=code>import time
      # Simulate long-running vulnerability scan
      time.sleep(45)
      print('Security scan completed!')</parameter>
      <parameter=timeout>50</parameter>
      </function>

      # Use IPython magic commands for package management and profiling
      <function=python_action>
      <parameter=action>execute</parameter>
      <parameter=code>%pip install requests
      %time response = requests.get('https://httpbin.org/json')
      %whos</parameter>

      # Analyze requests for potential vulnerabilities
      <function=python_action>
      <parameter=action>execute</parameter>
      <parameter=code># Filter for POST requests that might contain sensitive data
      post_requests = list_requests(
          httpql_filter="req.method.eq:POST",
          page_size=20
      )

      # Analyze each POST request for potential issues
      for req in post_requests.get('requests', []):
          request_id = req['id']
          # View the request details
          request_details = view_request(request_id, part="request")

          # Check for potential SQL injection points
          body = request_details.get('body', '')
          if any(keyword in body.lower() for keyword in ['select', 'union', 'insert', 'update']):
              print(f"Potential SQL injection in request {request_id}")

              # Repeat the request with a test payload
              test_payload = repeat_request(request_id, {
                  'body': body + "' OR '1'='1"
              })
              print(f"Test response status: {test_payload.get('status_code')}")

              print("Security analysis complete!")</parameter>
        </function>
      </examples>
  </tool>
</tools>
